Reputation: 187
I understand how to pass a variable from a controller to a form through the createForm
method, but what if I need to pass that value to a form embedded in the form I am called createForm on? I never explicitly call createForm anywhere on the embedded form, so how am I supposed to get that value to it? It is worth noting the value I am trying to pass is available through a service, but I can't call $this->get('serviceName')->getValue()
because I am not in a controller. For reference, this is how I get the value to the parent form, note how I do it through the createForm method, not the contructor:
//in a controller
$form = $this->createForm(new FormType(), $formObject, array('value' => $value));
Upvotes: 1
Views: 1601
Reputation: 10833
It's not because you are not in a controller that you cannot inject services (and parameters). Especially into types where each type can be a service. Sure, you can't do $this->get('serviceName')->getValue()
directly because the method get
is not available by default. However, you could inject the service into your form type. See another question I answered on dependency injection here for some information on how to inject services.
See this cookbook section which tells you how to transform your type into a service so you can inject your dependencies and at the same time, your value.
If for some reason you cannot transform your type into a service, then what you need to do is to pass your options to FormType
which will read them and pass the value
option to the embedded type. It is like a passing style design, you pass all you options to the main type, which will pass some of them to each sub types, than each sub types will pass them to their own sub types and so on. Again, you can take a look at this [cookbook recipe] for how to read options and use them in a custom form type.
In conclusion, I think it is easier to transform your type into a service.
Hope this helps you.
Regards,
Matt
Upvotes: 2