How to change form field value in symfony 2

symfony form group fields
symfony form options
symfony form->setdata
symfony 4 form validation
symfony form example
symfony form action
symfony form default value
symfony form events

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?

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

$form = $formBuilder->getForm();

$form->get('firstname')->setData('John');

How to Dynamically Modify Forms Using Form Events (Symfony Docs), Example: you have a "Product" form and need to modify/add/remove a field based on the 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 want the user to be able to change the name value once the object has been created. The getParent() method defines which is the form type used as the base of this type. In this case, the type extends from ChoiceType to reuse all of the logic and rendering of that field type. Note. The PHP class extension mechanism and the Symfony form field extension mechanism are not the same.

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 ...
    }
}

Forms (Symfony Docs), Changing the Action and HTTP Method; Changing the Form Name; Client-Side You need to deal with rendering HTML form fields, validating submitted data, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Notice how the rendered task input field has the value of the task property from the  When you create a form, each field initially displays the value of the corresponding property of the form's domain data (e.g. if you bind an object to the form). If you want to override this initial value for the form or an individual field, you can set it in the data option:

class ItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ...
            ->add('tags','text',array(
                'required' => false,
                'attr' => array('name' => 'tags','value'=>'newvalue'),
                'mapped' => false))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\ItemBundle\Entity\Item',
            'cascade_validation' => true,
        ));
    }
}

How to Customize Form Rendering (Symfony Docs), Some form field types have additional rendering options that can be passed to If you need to render form fields "by hand" then you can access individual values for 1 2. {# render the form and change the submission method #} {{ form(form,  In this article you'll learn how to make single customizations to one or more fields of your forms. If you need to customize all your forms in the same way, create instead a form theme or use any of the built-in themes, such as the Bootstrap theme for Symfony forms.

Another way to set the value is to use form options:

class ItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('tags','text',array(
                'required' => false,
                'attr' => array('name' => 'tags'),
                'mapped' => false,
                'data' => $options['tags_value'],
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\ItemBundle\Entity\Item',
            'cascade_validation' => true,
            'tags_value' => 'default value if you want',
        ));
    }

And then in controller:

public function editAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('MyBundleItemBundle:Item')->find($id);
    $form = $this->createForm(new ItemType(), $entity, ['tags_value' => 'test text']);
}

FormType Field (Symfony Docs), Its value is rendered as the action attribute of the form element. An empty value is Setting by_reference to false ensures that the setter is called in all cases. To explain this further, here's a simple example: 1 2 3 4 5 6 7 8 9 10 11 12 13. This option is inherited by the child types. With the code above, the label of the street field of both forms will use the form.address.street keyword message. Two variables are available in the label format: %id% A unique identifier for the field, consisting of the complete path to the field and the field name (e.g. profile_address_street); %name%

TextType Field (Symfony Docs), Rendered as input text field Inherited options attr data disabled empty_data error_bubbling When you create a form, each field initially displays the value of the corresponding 1 2 3. {{ form_help(form.name, 'Your name', { 'help_attr': {'​class': 'CUSTOM_LABEL_CLASS'} }) }} Setting to false will suppress the label. Symfony provides a "form builder" object which allows you to describe the form fields using a fluent interface. Later, this builder creates the actual form object used to render and process contents. Creating Forms in Controllers ¶ If your controller extends from the AbstractController , use the createFormBuilder () helper:

Forms (Symfony 2.0 Book), Symfony2 integrates a Form component that makes dealing with forms easy. Because your users will need to edit and create tasks, you're going to need to Before moving on, notice how the rendered task input field has the value of the  How to Dynamically Modify Forms Using Form Events¶ Often times, a form can't be created statically. In this article, you'll learn how to customize your form based on three common use-cases: Customizing your Form Based on the Underlying Data

How to Create a Custom Form Field Type (Symfony Docs), Symfony comes with tens of form types (called "form fields" in other projects) ready to 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 '​bool'); // optionally you can transform the given values for the options to // simplify the  Symfony2: How to set default value for a field DateTime Month 01 and Year 2011 but when I edit a record, Symfony change my original value, for example 2016-03-25

Comments
  • You can do in your case: $form->get('fieldName')->setData('my_value'); This works also for Symfony 3.
  • Could you please provide me an example?
  • I just want to say that this method is working for me when I do not provide entity to form, otherwise this will help stackoverflow.com/questions/13249485/…
  • This didn't work for me, but simply doing $form->setData(array('field'=>'value')) works.
  • This is the correct way to do it if you're running a modern version of Symfony. If this doesn't work for you, upgrade or figure out why it's not working.
  • $form-bind() is obsolete since Symfony 2.3 and is expected to be removed in 3.0. One should use $form->handleRequest($request) instead in the newer versions.
  • I need to change it inside controller action
  • where is the controller action?