doremi
doremi

Reputation: 15329

Symfony 2 - Add Field to

In my controller, I have:

$form = $this->createForm(new ResetPassword());

ResetPassword is an AbstractType class with it's own buildForm() method that I'm using to ->add some fields as is.

In my controller, I want to be able to add another field to the form before I display it.

Here's what I'm trying:

$form = $this->createForm(new ResetPassword())->add('test');

This generates an error:

Catchable Fatal Error: Argument 1 passed to Symfony\Component\Form\Form::add() must implement interface Symfony\Component\Form\FormInterface, string given

Upvotes: 0

Views: 754

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

There is a much better approach that let you keep working in a clean MVC structure. So, better is to use "Form events" to dynamically generate your forms.

For example, by adding an event subscriber to your Form, you delegate the creation of your fields to that Subscriber. You can then add the fields you want inside your subscriber according to your "EventType".

Adding An Event Subscriber To A Form Class

How to Dynamically Generate Forms Using Form Events

Upvotes: 3

Related Questions