Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change form field value in symfony 2

Tags:

I have a form like below:

class ItemType extends AbstractType {     public function buildForm(FormBuilderInterface $builder, array $options)     {         $builder             // ...             ->add('tags','text',array(                 'required' => false,                 'attr' => array('name' => 'tags'),                 'mapped' => false))         ;     }      public function setDefaultOptions(OptionsResolverInterface $resolver)     {         $resolver->setDefaults(array(             'data_class' => 'MyBundle\ItemBundle\Entity\Item',             'cascade_validation' => true,         ));     } } 

My edit action

public function editAction(Request $request, $id) {     $em = $this->getDoctrine()->getManager();     $entity = $em->getRepository('MyBundleItemBundle:Item')->find($id);     $form = $this->createForm(new ItemType(), $entity);     //$form->get('tags')->setValue('test text');     // ^- this is what i would like to do -^     // ... } 

While I am editing an item, How can I change form field value inside controller before rendering it?

like image 701
dextervip Avatar asked Jul 04 '13 20:07

dextervip


2 Answers

You can use setData() to set data on form fields in Symfony, like this:

$form = $formBuilder->getForm();  $form->get('firstname')->setData('John'); 
like image 153
Rick Pastoor Avatar answered Oct 13 '22 08:10

Rick Pastoor


You can change tags value in the controller:

$request = $this->get('request');     if ($request->getMethod() == 'POST')  {     $form->bind($request);     if $form->isValid())     {         $entity->setTags('test');         //persist ...     } } 
like image 20
meherzi.sahbi Avatar answered Oct 13 '22 08:10

meherzi.sahbi