Symfony 2.5 implemented handy multiple file upload support, e.g. input fields that look like this:
<input id="form_resumes" multiple="multiple" name="form[documents][]" required="required" type="file" />
Unfortunately there seem to be some problems in the Validator
component. For example, it’s difficult to require at least one file. Likewise the All
constraint doesn’t play nicely with validation groups. Here are a few workarounds.
To require at least one file but not more than three, use the Count
constraint in combination with All
and NotNull
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$builder = $this->createFormBuilder(); $form = $builder ->add('documents', 'file', array( 'required' => false, 'multiple' => true, 'constraints' => array( new Count(array('max'=>3), new All(array( 'constraints' => array( new NotNull() ) )) ) )) ->add('submit', 'submit') ->getForm() ; |
This works around a bug where 'min'=>1
is ignored.
If you’re using validation groups, you may notice that the All
constraint is not being applied. Here’s how to fix it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$builder = $this->createFormBuilder(null, array( 'validation_groups' => 'Test' )); $form = $builder ->add('documents', 'file', array( 'required' => false, 'multiple' => true, 'constraints' => array( new Count(array('min'=>1, 'groups'=>'Test')), new All(array( 'groups' => 'Test', 'constraints' => array( new NotNull(array('groups'=>'Test')) ) )) ) )) ->add('submit', 'submit') ->getForm() ; |
Note line 11: 'groups' => 'Test',
Technically we shouldn’t have to specify validation groups for the All
constraint; in fact there seems to be no way to do this in YAML. Hacking it in as an option to All
on the PHP side however seems to be working for me. YMMV. And as far as I can tell this last one is fixed in 2.6.