Prepopulate form fields

1.1k views Asked by At

I have a user creation form (on top of Symfony Form component), it's used on some different pages and is loaded via AJAX.

An initial request contains information we already know about a user-to-be, e.g. if form is loaded from a manager creation page for the "X" company, we already know that a user has a role = "manager" and company = "X". And the corresponding form fields must be removed/hidden from the form and underlying user object must be provided with these parameters (a role field must be set to "manager", a company field must be set to "X").

How can it be achieved?

1

There are 1 answers

6
Simon Duflos On BEST ANSWER

From what I understand you can use the answer for this question : https://stackoverflow.com/a/18792299/4098335

Basically, after calling createForm(), you have to call setData() for the desired field.

If this doesn't work, maybe try overriding the constructor for your AbstractType class. But it's a bit "hacky" and clearly not the easiest way... Example here :

class YourUserType extends AbstractType
{
    protected $manager;

    public function __construct($manager = null)
    {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($this->manager !== null) {
            $builder
                ->add('manager', 'entity', array(
                        'class' => 'YourBundle:Manager',
                        'data' => $this->manager,
                        'read_only' => true,
                    )
                );
        }
    }
}

Then, in your controller, pass the "manager" entity when you instantiate YourUserType :

    $form = $this->createForm(new YourUserType($manager), $entity, array(
        'action' => $this->generateUrl('create_url'),
        'method' => 'POST',
    ));

Note: in the example I put the 'read_only' option to true, that way you'll 'avoid' the user to select another value. You can hide the field anyway later in front end, but still you should check the value later when dealing with the form request.