1212namespace Symfony \Component \Form \Extension \Core \Type ;
1313
1414use Symfony \Component \Form \AbstractType ;
15+ use Symfony \Component \Form \FormBuilderInterface ;
16+ use Symfony \Component \Form \FormEvent ;
17+ use Symfony \Component \Form \FormEvents ;
1518use Symfony \Component \Form \FormInterface ;
1619use Symfony \Component \Form \FormView ;
20+ use Symfony \Component \OptionsResolver \Options ;
1721use Symfony \Component \OptionsResolver \OptionsResolver ;
1822
1923class FileType extends AbstractType
2024{
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 (not 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+
2146 /**
2247 * {@inheritdoc}
2348 */
@@ -39,20 +64,26 @@ public function buildView(FormView $view, FormInterface $form, array $options)
3964 */
4065 public function finishView (FormView $ view , FormInterface $ form , array $ options )
4166 {
42- $ view
43- ->vars ['multipart ' ] = true
44- ;
67+ $ view ->vars ['multipart ' ] = true ;
4568 }
4669
4770 /**
4871 * {@inheritdoc}
4972 */
5073 public function configureOptions (OptionsResolver $ resolver )
5174 {
75+ $ dataClass = function (Options $ options ) {
76+ return $ options ['multiple ' ] ? null : 'Symfony\Component\HttpFoundation\File\File ' ;
77+ };
78+
79+ $ emptyData = function (Options $ options ) {
80+ return $ options ['multiple ' ] ? array () : null ;
81+ };
82+
5283 $ resolver ->setDefaults (array (
5384 'compound ' => false ,
54- 'data_class ' => ' Symfony\Component\HttpFoundation\File\File ' ,
55- 'empty_data ' => null ,
85+ 'data_class ' => $ dataClass ,
86+ 'empty_data ' => $ emptyData ,
5687 'multiple ' => false ,
5788 ));
5889 }
0 commit comments