[Form] Forms now don't create empty objects anymore if they are completely empty and not required. The empty data for these forms is null.

This commit is contained in:
Bernhard Schussek 2012-02-02 14:30:38 +01:00
parent 0914a38e74
commit bd461e295d
4 changed files with 43 additions and 3 deletions

View File

@ -200,6 +200,8 @@ To get the diff between two versions, go to https://github.com/symfony/symfony/c
model
* added options "adder_prefix" and "remover_prefix" to collection and choice
type
* forms now don't create an empty object anymore if they are completely
empty and not required. The empty value for such forms is null.
### HttpFoundation

View File

@ -156,7 +156,11 @@ class FieldType extends AbstractType
}
if ($class) {
$defaultOptions['empty_data'] = function () use ($class) {
$defaultOptions['empty_data'] = function (FormInterface $form) use ($class) {
if ($form->isEmpty() && !$form->isRequired()) {
return null;
}
return new $class();
};
} else {

View File

@ -517,7 +517,7 @@ class Form implements \IteratorAggregate, FormInterface
}
// Merge form data from children into existing client data
if (count($this->children) > 0 && $this->dataMapper) {
if (count($this->children) > 0 && $this->dataMapper && null !== $clientData) {
$this->dataMapper->mapFormsToData($this->children, $clientData);
}

View File

@ -178,18 +178,52 @@ class FieldTypeTest extends TypeTestCase
{
$form = $this->factory->create('form', null, array(
'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
'required' => false,
));
$form->add($this->factory->createNamed('field', 'firstName'));
$form->add($this->factory->createNamed('field', 'lastName'));
$form->setData(null);
$form->bind(array('firstName' => 'Bernhard'));
// partially empty, still an object is created
$form->bind(array('firstName' => 'Bernhard', 'lastName' => ''));
$author = new Author();
$author->firstName = 'Bernhard';
$author->setLastName('');
$this->assertEquals($author, $form->getData());
}
public function testBindEmptyWithEmptyDataCreatesNoObjectIfNotRequired()
{
$form = $this->factory->create('form', null, array(
'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
'required' => false,
));
$form->add($this->factory->createNamed('field', 'firstName'));
$form->add($this->factory->createNamed('field', 'lastName'));
$form->setData(null);
$form->bind(array('firstName' => '', 'lastName' => ''));
$this->assertNull($form->getData());
}
public function testBindEmptyWithEmptyDataCreatesObjectIfRequired()
{
$form = $this->factory->create('form', null, array(
'data_class' => 'Symfony\Tests\Component\Form\Fixtures\Author',
'required' => true,
));
$form->add($this->factory->createNamed('field', 'firstName'));
$form->add($this->factory->createNamed('field', 'lastName'));
$form->setData(null);
$form->bind(array('firstName' => '', 'lastName' => ''));
$this->assertEquals(new Author(), $form->getData());
}
/*
* We need something to write the field values into
*/