Skip to content

Commit a72c5c4

Browse files
committed
[Form] Return empty array when no file is uploaded
1 parent 2e043a5 commit a72c5c4

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/Symfony/Component/Form/Extension/Core/Type/FileType.php

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,31 @@
1212
namespace Symfony\Component\Form\Extension\Core\Type;
1313

1414
use Symfony\Component\Form\AbstractType;
15+
use Symfony\Component\Form\Extension\Core\DataTransformer\FilesToArrayTransformer;
16+
use Symfony\Component\Form\FormBuilderInterface;
17+
use Symfony\Component\Form\FormEvent;
18+
use Symfony\Component\Form\FormEvents;
1519
use Symfony\Component\Form\FormInterface;
1620
use Symfony\Component\Form\FormView;
1721
use Symfony\Component\OptionsResolver\Options;
1822
use Symfony\Component\OptionsResolver\OptionsResolver;
1923

2024
class FileType extends AbstractType
2125
{
26+
/**
27+
* {@inheritdoc}
28+
*/
29+
public function buildForm(FormBuilderInterface $builder, array $options)
30+
{
31+
if ($options['multiple']) {
32+
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
33+
if (array(null) === $event->getData()) {
34+
$event->setData($event->getForm()->getConfig()->getEmptyData());
35+
}
36+
});
37+
}
38+
}
39+
2240
/**
2341
* {@inheritdoc}
2442
*/
@@ -52,10 +70,14 @@ public function configureOptions(OptionsResolver $resolver)
5270
return $options['multiple'] ? null : 'Symfony\Component\HttpFoundation\File\File';
5371
};
5472

73+
$emptyData = function (Options $options) {
74+
return $options['multiple'] ? array() : null;
75+
};
76+
5577
$resolver->setDefaults(array(
5678
'compound' => false,
5779
'data_class' => $dataClass,
58-
'empty_data' => null,
80+
'empty_data' => $emptyData,
5981
'multiple' => false,
6082
));
6183
}

src/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ public function testSubmitEmpty()
4444
$this->assertNull($form->getData());
4545
}
4646

47+
public function testSubmitEmptyMultiple()
48+
{
49+
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FileType', null, array(
50+
'multiple' => true,
51+
))->getForm();
52+
53+
// submitted data when an input file is uploaded without choosing any file
54+
$form->submit(array(null));
55+
56+
$this->assertSame(array(), $form->getData());
57+
}
58+
4759
public function testSetDataMultiple()
4860
{
4961
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FileType', null, array(

0 commit comments

Comments
 (0)