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.
