![](/img/trans.png)
[英]I am using OG module at Drupal 8. How to add role and role's permission for particular group here?
[英]How to add role to group using constructor
我曾嘗試在他們創建時為每個組設置角色。 我認為使用 __constructor 是個好主意,但它不起作用,ROLE_ADMIN 不在新組中。 我不知道我做錯了什么。
<?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();
}
}
文檔說得最好:
僅當您使用
new
關鍵字構造新實例時,才會調用實體的構造函數。 Doctrine 從不調用實體構造函數,因此您可以隨意使用它們,甚至需要任何類型的 arguments。
來源: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/architecture.html
因此,本質上,除非您將角色實際存儲在數據庫中,否則當從 db 加載 object 時,您的構造函數是無關緊要的。 有一些方法可以解決這個問題,您可以覆蓋您的getRoles
方法以在那里添加額外的角色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.