A lot of tutorials are showing you how to create embedded forms with associations/relations — what about unrelated entities?
I figured out you can pass the second entity as a parameter to the parent form, pass it normally to the embedded form via the ‘data’ parameter, which will let the embedded form update the object. Then just persist() the object back in the controller like normal. No crazy data/request wrangling necessary!
In the parent form:
//...
private $userConfig = null;
public function __construct($userConfig = null) {
$this->userConfig = $userConfig;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
//...
$builder->add('userConfig', new UserConfigPartialType(), array(
'label' => false,
'required' => false,
'mapped' => false,
'data' => $this->userConfig
));
//...
}
In the controller:
$form = $this->createForm(new Forms\UserType($userConfig), $user);
$form->handleRequest($request);
if($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($userConfig);
$em->persist($user);
$em->flush();
}
The UserConfigPartialType form is just a normal form with a couple form fields. Of course ideally you’d have a relationship between these entities, but this is nice if for some reason you can’t (like Doctrine’s bidirectionality being a pain in the butt.)
Hi,good post. but i have a question.
I have a entity without relations with another entity. This is call logTask.
I have 3 fields: id, date, task
I have a controller and i make a form, this form have 3 fields, and works, this form ask:
Intial date and final date:
Then i list all the entity rows, but, i dont know how can i make a form for edit this records.
If you can help me, thanks very much.
IIf you don’t want to use sett injection you can simply parse custom data to your form through the defaultOptions:
http://stackoverflow.com/questions/10920006/pass-custom-options-to-a-symfony2-form#10922788
Then your data will be available this way:
‘data’ => $options[‘userConfig’]
@webDEVILopers, could you elaborate? I don’t see how the example linked would get the data into / out of the form. How would you rewrite the sample code in my blog post? Thanks for your contribution!
Update: webDEVILopers has kindly explained a better way of passing data to the form; see the comments here: https://gist.github.com/zyphlar/b98e054526a3d0dc26e3