Search code examples
phpsymfonydoctrinerelational-databasesymfony-3.2

Symfony 3, ManyToOne relation in form


I have a few Entities and I try to setup relations between users and permissions. I want to have possibility to assign group of permissions to user, so I created entity User, GroupAssociationsUser, Permissions. I though that best way is to create relation ManyToOne in GroupAssociationsUser to Users and to Permissions. Bellow you can see code of GroupAssociationsUser entity:

/**
 * @ORM\ManyToOne(targetEntity="Permissions", inversedBy="group_assoc_user")
 * @ORM\JoinColumn(name="group_permissions", referencedColumnName="id", nullable=FALSE)
 */
private $group_permissions;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="group_assoc_user")
 * @ORM\JoinColumn(name="user_assoc", referencedColumnName="id", nullable=FALSE)
 */
private $user_assoc;

Then I also created relation in User entity:

/**
 * @ORM\OneToMany(targetEntity="GroupAssociationsUser", mappedBy="user_assoc")
 */
private $group_assoc_user;


public function __construct()
{
    $this->group_assoc_user = new ArrayCollection();
}

Finally in Permission entity:

/**
* @ORM\OneToMany(targetEntity="GroupAssociationsUser", mappedBy="group_permissions")
*/
private $group_assoc_user;

public function __construct()
{
$this->group_assoc_user = new ArrayCollection();
}

So basically I want to have select list on my user edit page and I want to have possibility to select permission group to assign to user.

So I created form with:

->add('group_assoc_user', EntityType::class, array(
            'class' => 'AppBundle:Permissions',
            'choice_label'=> 'group_name',
            'placeholder' => 'no rights',
        ))

And the problem is that no mater what I do, I have got only list of exiting permissions or if I change code to :

        ->add('group_assoc_user', EntityType::class, array(
            'class' => 'AppBundle:GroupAssociationsUser',
            'choice_label'=> 'Permissions.group_name',
            'placeholder' => 'no rights',
        ));

I have got listed only assigned permission without not assigned. What am I doing wrong?

Even if I got all permissions names how I can force doctrine to mark already assigned field?


Solution

  • Try to set Multiple to true.

    http://symfony.com/doc/current/reference/forms/types/entity.html#multiple

        ->add('group_assoc_user', EntityType::class, array(
            'class' => 'AppBundle:GroupAssociationsUser',
            'choice_label'=> 'Permissions.group_name',
            'placeholder' => 'no rights',
            'multiple' => true,
        ));
    

    You may also like the

    'expanded' => true
    

    option