Two Unrelated (No association) Entities in One Form in Symfony2

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);
if($form->isValid()) {
$em = $this->getDoctrine()->getManager();

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.)


4 thoughts on “Two Unrelated (No association) Entities in One Form in Symfony2

  1. Gabriel says:

    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.

  2. @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!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s