Reputation: 8694
I'm new to Symfony forms and am trying to figure out how to have a form with a hidden field that references the parent object. For example, I have a list that has a many-to-one relationship with contacts. When creating a new contact, there needs to he a hidden field with the id of the list that the contact is being added to.
Currently I am attempting to embed a form called ListIdType
in my ContactType
form. The only field in the ListIdType
form is the id of the list. This works nicely because I can set the list on an empty contact entity and it will automatically populate an element in the form named contact[list][id]
(which is defined in the ListIdType
form). The problem with this is that when I submit the form, I get an error saying that neither element "id" or methed "setId()" exists in the list class.
My but feeling is that I'm doing something wrong, but I can't find any documentation to point me in the right direction.
Upvotes: 5
Views: 7289
Reputation: 3303
Recently I've found Gregwar's Forum bundle, which adds entity_id form type. It does automatically most of needed transformations and might be just what you need.
https://github.com/Gregwar/FormBundle
Upvotes: 3
Reputation: 8694
The solution that I came up with is to add a hidden field with the property_path
option set to FALSE
. Here is the code in ContactType::buildForm
:
$builder->add('list_id', 'hidden', array(
'data' => $data->getList()->getId(),
'property_path' => FALSE,
));
I then handle the field in my controller.
This works but doesn't feel like the best solution to me. I'm still open if someone can suggest a better way!
Upvotes: 6