Hello.
Now I would like to make life easier for all those people who write their projects based on the
Symfony 2 framework.
In symfony 2, there are excellent tools for creating forms from entities, and also, more interestingly,
combined forms .
')
So, if you need to set default values ​​from entities (objects) to such (combined) form, then you (like me) will wander around the Internet, looking for a solution to this problem, since seemingly in the documentation there is no such thing (in any case, I did not find it).
And so ... I generated the form on the fly (in the controller) as follows:
$client = $this->getDoctrine()->getRepository('CarrierUserBundle:Client') ->findOneBy(array('id' => (int) $id)); $form = $this->createFormBuilder()->add('user', new UserType()) ->add('client', new ClientType()) ->getForm();
In this case, I could not set the default values ​​from the User and Client objects (it is worth noting that there is a “User one to many Clients” between these objects). After a long search, I stumbled upon only half the solution to the problem, and coped with the rest myself. So, the actual solution:
$client = $this->getDoctrine()->getRepository('CarrierUserBundle:Client') ->findOneBy(array('id' => (int) $id)); $form = $this->createForm(new Form\ClientType(), $client) ->add($this->createForm(new Form\UserType()));
We see that instead of
createFormBuilder , I use directly
createForm , into which the form type and the object are passed (the object, in fact, takes the default values). After that, another is attached to the same form using the
add method, but
$ user is no longer passed to it, because
$ client has a
getUser () method, for this I mentioned the links between entities.
I hope I saved some time. Use
Symfony 2 and talk about your decisions, then it will be easier for all of us to do our work =)
Read also:
Sluggable, Timestampable, and so on in Symfony 2