Maybe I'm missing the obvious but how do I (or can I) add an extra "unbound" field to a Symfony form that is otherwise bound to an entity?
Let's say I have an entity with fields first_name
and last_name
. I do the typical thing in my form class buildForm
method.
$builder
->add('first_name')
->add('last_name')
;
and this in my controller:
$editForm = $this->createForm(new MyType(), $entity);
That works nicely but I'd like to add another text box, let's call it "extra", and receive the value in the POST action. If I do $builder->add('extra')
, it complains that
NoSuchPropertyException in PropertyAccessor.php line 479:
Neither the property "extra" nor one of the methods "getExtra()", "extra()", "isExtra()", "hasExtra()", "__get()" exist and have public access in class...
Which is correct. I just want to use it to collect some extra info from the user and do something with it other than storing it with the entity.
I know how to make a completely standalone form but not one that's "mixed". Is this possible?
In your form add a text field with a false property_path:
$builder->add('extra', 'text', array('property_path' => false));
You can then access the data in your controller:
$extra = $form->get('extra')->getData();
UPDATE
The new way since Symfony 2.1 is to use the mapped
option and set that to false
.
->add('extra', null, array('mapped' => false))
Credits for the update info to Henrik Bjørnskov ( comment below )