允许用户仅在奏鸣曲中编辑其实体

时间:2014-10-07 09:18:44

标签: php symfony sonata-admin

我想允许一些用户添加新闻,但我也不希望他们编辑其他新闻。所以在登录管理员面板之后,他们应该只能看到他们的新品。我现在正在用奏鸣曲做这件事。

这有什么配置吗?

我的service.yml:

services:
    sonata.admin.news:
        class: MyBundle\Admin\NewsAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "News" }
        arguments:
            - ~
            - MyBundle\Entity\News
            - ~
            - "@doctrine.orm.entity_manager"
        calls:
            - [ setTranslationDomain, [MyBundle]]

NewsAdmin包含常规内容,因此无需将其放在此处。

1 个答案:

答案 0 :(得分:1)

您可以将安全上下文服务注入NewsAdmin

class NewsAdmin extends Admin
{
    protected $security;
    protected $em;

    public function __construct($code, $class, $baseControllerName, $entityManager, SecurityContext $security)
    {
        parent::__construct($code, $class, $baseControllerName);

        $this->em = $entityManager;
        $this->security = $security;
    }

    public function getNewInstance()
    {
        $news = parent::getNewInstance();
        $news->setUser($this->security->getToken()->getUser());

        return $formDefinition;
    }

    public function createQuery($context = 'list')
    {
        $queryBuilder = $this->getModelManager()->getEntityManager($this->getClass())->createQueryBuilder();

        $queryBuilder
            ->select('news')
            ->from($this->getClass(), 'news')
            ->andWhere('news.user = :user')
            ->setParameter(':user', $this->security->getToken()->getUser());

        $proxyQuery = new ProxyQuery($queryBuilder);
        return $proxyQuery;
    }

在您的管理员定义中:

services:
    sonata.admin.news:
        class: MyBundle\Admin\NewsAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "News" }
        arguments:
            - ~
            - MyBundle\Entity\News
            - ~
            - "@doctrine.orm.entity_manager"
            - "@security.context"
        calls:
            - [ setTranslationDomain, [MyBundle]]