Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form - How to have hidden field reference parent object

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.

like image 790
Icode4food Avatar asked Nov 18 '11 17:11

Icode4food


2 Answers

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!

like image 139
Icode4food Avatar answered Nov 17 '22 18:11

Icode4food


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

like image 20
Tomasz Struczyński Avatar answered Nov 17 '22 17:11

Tomasz Struczyński