Symfony 2 - modifying form configuration after ini

2019-09-19 12:12发布

问题:

I was wondering if it's possible to modify form configuration after the form object has been initialized (I define my form as a service).

Namely, when creating a form in a controller, we could do this:

$form = $this->createForm('some_form_type', $entity, ['some_key' => true]);

but then what if I want to modify $options after initialization.

FormInterface exposes getConfig() method that returns FormConfigInterface so we have direct access to the configuration object. This object, however, does not expose any setters. FormInterface also does not expose any configuration setter methods.

In short, do you know of a way to modify a form configuration object after initilizaing the form object?

回答1:

First question I'd like to ask you is: Why would you modify the form configuration after the form object is built ?

That's actually impossible, because the configuration is locked before being used by the form builder (FormBuilderInterface) in order to create and initialize the form (FormInterface) instance.

So, unless you use your own FormBuilderInterface and FormConfigBuilder instances not locking the configuration once build, you should use the form builder to properly modify anything before building the form instance.



标签: forms symfony