Skip to content

Commit 0aeb078

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

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

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

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

1414
use Symfony\Component\Form\AbstractType;
15+
use Symfony\Component\Form\FormBuilderInterface;
16+
use Symfony\Component\Form\FormEvent;
17+
use Symfony\Component\Form\FormEvents;
1518
use Symfony\Component\Form\FormInterface;
1619
use Symfony\Component\Form\FormView;
1720
use Symfony\Component\OptionsResolver\Options;
1821
use Symfony\Component\OptionsResolver\OptionsResolver;
1922

2023
class FileType extends AbstractType
2124
{
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+
2246
/**
2347
* {@inheritdoc}
2448
*/
@@ -52,10 +76,14 @@ public function configureOptions(OptionsResolver $resolver)
5276
return $options['multiple'] ? null : 'Symfony\Component\HttpFoundation\File\File';
5377
};
5478

79+
$emptyData = function (Options $options) {
80+
return $options['multiple'] ? array() : null;
81+
};
82+
5583
$resolver->setDefaults(array(
5684
'compound' => false,
5785
'data_class' => $dataClass,
58-
'empty_data' => null,
86+
'empty_data' => $emptyData,
5987
'multiple' => false,
6088
));
6189
}

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)