|
12 | 12 | namespace Symfony\Component\Form\Extension\Core\Type;
|
13 | 13 |
|
14 | 14 | use Symfony\Component\Form\AbstractType;
|
| 15 | +use Symfony\Component\Form\FormBuilderInterface; |
| 16 | +use Symfony\Component\Form\FormEvent; |
| 17 | +use Symfony\Component\Form\FormEvents; |
15 | 18 | use Symfony\Component\Form\FormInterface;
|
16 | 19 | use Symfony\Component\Form\FormView;
|
17 | 20 | use Symfony\Component\OptionsResolver\Options;
|
18 | 21 | use Symfony\Component\OptionsResolver\OptionsResolver;
|
19 | 22 |
|
20 | 23 | class FileType extends AbstractType
|
21 | 24 | {
|
| 25 | + /** |
| 26 | + * {@inheritdoc} |
| 27 | + */ |
| 28 | + public function buildForm(FormBuilderInterface $builder, array $options) |
| 29 | + { |
| 30 | + if ($options['multiple']) { |
| 31 | + $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { |
| 32 | + $form = $event->getForm(); |
| 33 | + $data = $event->getData(); |
| 34 | + |
| 35 | + // submitted data for an input file (no required) without choosing any file |
| 36 | + if (array(null) === $data) { |
| 37 | + $emptyData = $form->getConfig()->getEmptyData(); |
| 38 | + |
| 39 | + $data = is_callable($emptyData) ? call_user_func($emptyData, $form, $data) : $emptyData; |
| 40 | + $event->setData($data); |
| 41 | + } |
| 42 | + }); |
| 43 | + } |
| 44 | + } |
| 45 | + |
22 | 46 | /**
|
23 | 47 | * {@inheritdoc}
|
24 | 48 | */
|
@@ -52,10 +76,14 @@ public function configureOptions(OptionsResolver $resolver)
|
52 | 76 | return $options['multiple'] ? null : 'Symfony\Component\HttpFoundation\File\File';
|
53 | 77 | };
|
54 | 78 |
|
| 79 | + $emptyData = function (Options $options) { |
| 80 | + return $options['multiple'] ? array() : null; |
| 81 | + }; |
| 82 | + |
55 | 83 | $resolver->setDefaults(array(
|
56 | 84 | 'compound' => false,
|
57 | 85 | 'data_class' => $dataClass,
|
58 |
| - 'empty_data' => null, |
| 86 | + 'empty_data' => $emptyData, |
59 | 87 | 'multiple' => false,
|
60 | 88 | ));
|
61 | 89 | }
|
|
0 commit comments