Sean Powell
Sean Powell

Reputation: 1437

Creating join entities from a form

I have three entities, User, Provider and UserProvider (a join entity with some extra data).

I'm trying to create a form where the user specifies their providers by ticking boxes (which should generate some UserProvider records).

I've tried using choices and generating a new form type but can't seem to get it working correctly. This is the last thing I tried:

$form = $this->createFormBuilder($user)
    ->add('userProviders', 'entity', array(
        'class' => 'MyAppBundle:UserProvider',
        'property' => 'provider.name'
        'choices' => $userProviders
    ))
    ->getForm();

Where $userProviders is an array of some entities I generated mapping the current user to all possible providers, but this won't work because the entities are not persisted (as they may not be needed).

What is the cleanest way to do this in Symfony?

Upvotes: 0

Views: 91

Answers (2)

Sean Powell
Sean Powell

Reputation: 1437

As a solution to this I just created a unbound form listing Providers and persisted them, along with the current User as UserProviders.

This isn't ideal, as revisiting the form won't show the existing join entities (UserProvider) and additional work is needed to make those visible.

Upvotes: 0

Schwierig
Schwierig

Reputation: 712

Just use the internal way of the entity form class to generate your array like this:

use Doctrine\ORM\EntityRepository;
// ...

$builder->add('userProviders', 'entity', array(
    'class' => 'MyAppBundle:UserProvider',
    'property' => 'provider.name'
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('u')
            //Your Query here
        ;
    },
));

Taken from here: http://symfony.com/doc/master/reference/forms/types/entity.html

You can do everything you want inside there, even 2 queries for possible NOT IN cases.

Upvotes: 1

Related Questions