undefinedman
undefinedman

Reputation: 670

How to map two entities in the one Symfony Form

The problem I am having now is related to entities and forms in Symfony2.

While creating the form that refers to one entity I can simply wire it by saying:

$user = new User();
$form->createForm(new UserType(), $user);
...
$manager->persist($user);
$manager->flush();

And that is working fine. But the problem raises when I have more complex form that is built based on other forms, e.g.

So, let's imagine I have a form called RegistrationType that contains two other forms called UserType wired to User entity and ProfileType wired to Profile entity.

Now, how can I handle that in the controller? I mean, I cannot do something like:

$user = new User();
$profile = new Profile();
$form->createForm(new RegisterType(), $user, $profile);
OR
$form->createForm(new RegisterType(), [$user, $profile]);
...
$manager->persist($user);
$manager->flush();

$profile->setUserId($user->getId());
$manager->persist($profile);
$manager->flush();

If I pass only $user, like so

$form->createForm(new RegisterType(), $user);

Symfony will complain that there are properties that are not mapped, of course I can set them to 'mapped' => false but then I have to set them later on manually.

What's the best way to handle this?

Thanks in advance!

Upvotes: 0

Views: 663

Answers (1)

Ziumin
Ziumin

Reputation: 4860

Create UserType, ProfileType and RegistrationType forms. RegistrationType should add UserType and ProfileType as its children. Create Registration DTO and set it as data_class for RegistrationType. Then you can write something like

$user = new User();
$profile = new Profile();
$form->createForm(new RegistrationType(), 
           new Registration($user, $profile));

Upvotes: 2

Related Questions