Search code examples
phpsymfonyfosuserbundlerolesusergroups

How to add role to group using constructor


I've been tried to set role to every group while they are creating. I thought using __constructor will be good idea, but it doesn't work, ROLE_ADMIN isn't in new groups. I don't know what I'm doing wrong.

<?php
// src/AppBundle/Entity/Group.php
namespace AppBundle\Entity;

use FOS\UserBundle\Model\Group as BaseGroup;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\GroupRepository")
 * @ORM\Table(name="d0s_groups")
 */
class Group extends BaseGroup
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Assert\NotBlank(
     *     message="Nazwa grupy nie może być pusta."
     * )
     * @Assert\Length(
     *      min = 3,
     *      max = 32,
     *      minMessage = "Nazwa grupy musi mieć conajmniej 3 znaki.",
     *      maxMessage = "Nazwa grupy może mieć maksymalnie 32 znaki."
     * )
     */
    protected $name;

    public function __construct($name, $roles = array())
    {
        parent::__construct($name, $roles);
        $this->addRole("ROLE_ADMIN");
    }

    public function getId() {
        return $this->id;
    }

    public function __toString()
    {
        return $this->getName();
    }
}

Solution

  • the documentation says it best:

    The constructor of an entity is only ever invoked when you construct a new instance with the new keyword. Doctrine never calls entity constructors, thus you are free to use them as you wish and even have it require arguments of any type.

    source: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/architecture.html

    So essentially, unless you actually store the roles in the database, your constructor is irrelevant when an object is loaded from db. There are ways around this, you could override your getRoles method to add the additional role there.