Question

I am getting trouble with symfony2 forms which is overriding my entity's data by null if the corresponding form input is not submitted.

Here is an example:

Form type:

$builder
    ->add('customerid', 'text')
    ->add('field1', 'text')
    ->add('field2', 'text')
    ...

Controller :

$customer = new Customer();
$customer->setId('the customerID');
$customerForm = $this->createForm(new CustomerType(), $customer);
if ($request->getMethod() == 'POST') {
    $customerForm->bind($request);
    ...
}

On the view, i don't render the customerid text field. Only others fields are submitted.

After submitting the form, $customerForm->bind($request); is overriding the previously setted customerID by null even if no empty value was submitted for it.

Is there any way to not override the value if the input fields was not rendered?

Here seems to be the same problem : https://github.com/symfony/symfony/issues/1341 A patch was submitted but i did not found documentation on how to use it.

Thanks

Was it helpful?

Solution

Any field in the form (whether rendered or not) will have a value, either null or the value of the field.

Which version of Symfony are you using?

I assume you're using <2.3 as I think bind was changed to submit at 2.3. With bind every field is merged into the object meaning it will replace the data, null or otherwise. I think the only way to work around this would be to either just not include the unwanted fields in the form or the use an event listener as documented in the cookbook.

If you are using 2.3+ (or you upgrade to 2.3+) then you should be using $form->submit() which has a second argument which allows you to set the form to not overwrite object properties if they are null. eg $form->submit($request->get($form->getName()), false) (true being the boolean to set/unset the overwrite, or $clearMissing on the actual code)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top