Setting a value to a hidden form symfony field
The case
Sometimes, when creating a new object, we need to give a default value to a specific field but we don’t want this field to be visible in the form.
A tipical example would it be a blog -> post relationship. Where we want the blog_id field to be set automatically but we want it to be hidden.

Blog->Post
The mistake
When creating a new post for a blog, we do not want the blog_id field to be visible, so we typically go to PostForm.class.php and unset the field blog_id:
//myproject/lib/form/PostForm.class.form class PostForm extends BasePostForm { public function configure() { unset( $this['blog_id'] ); } }
Then, we edit the action class and set a default value for the blog_id field:
// mypoject/modules/post/actions/actions.class.php class postActions extends sfActions { public function executeNew(sfWebRequest $request) { // create the form $form = new PostForm(); // get blog_id parameter from the request // and set the default value $form->setDefault("blog_id", $request->getParameter('blog_id') ); $this->form = $form; } //... rest of actions here ... }
Finally, when we try to create a new post, we realize that the blog_id has not been set correctly.
The solution
Instead of unsetting the blog_id field, we have to change its widget to a sfWidgetFormInputHidden:
//PostForm.class.form class PostForm extends BasePostForm { public function configure() { // the wrong way in this case // unset( $this['blog_id'] ); // the right way in this case $this->widgetSchema['blog_id'] = new sfWidgetFormInputHidden(); } }
This way the field blog_id remains hidden but do exists in the form, so the setDefault method works correctly.
Category: Symfony | Tags: actions, forms, Symfony, tips 8 comments »

July 18th, 2009 at 4:12 pm
Can i get a one small photo from your site?
July 20th, 2009 at 9:26 am
Yes. Which one do you want?
November 8th, 2009 at 12:20 am
I have a question. I want to disable a field while I edit. For example, in user creation. I want to allow user to set “username”. However, when they edit, they should not be able to edit the “username”. How can I disable a field depend on different action?
Thanks
November 10th, 2009 at 8:45 am
Hi,
In executeEdit get the schema of the form, and add a readonly attribute to the field you want. Something like this:
March 5th, 2010 at 8:22 am
Thank you! very usufeul information
March 13th, 2010 at 10:16 pm
I really like when people are expressing their opinion and thought. So I like the way you are writing
April 26th, 2010 at 4:36 pm
I have a question. I have to set a value for the hidden field in the create action and then save the form. I am using the default processForm action and I think that while binding my setDefault is overwritten .Is it possible to somehow insert the value alongside the input data submitted by the user to the form ?
June 7th, 2011 at 7:23 pm
Didnt work for new form.. to edit a form worked fine.