How to retrieve subject in Sonata configureListFields?

若如初见. 提交于 2019-12-11 06:16:18

问题


I use Sonata Admin Bundle in my Symfony project and created an ArticleAdmin class for my Article entity. In the list page, I added some custom actions to quickly publish, unpublish, delete & preview each article.

What I want to do is to hide publish button when an article is already published & vice versa.

To do this, I need to have access to each object in method configureListFields(). I would do something like this:

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper->add('title');
    // ...

    /** @var Article article */
    $article = $this->getSubject();

    // Actions for all items.
    $actions = array(
        'delete'  => array(),
        'preview' => array(
            'template' => 'AppBundle:ArticleAdmin:list__action_preview.html.twig',
        ),
    );

    // Manage actions depending on article's status.
    if ($article->isPublished()) {
        $actions['draft']['template'] = 'AppBundle:ArticleAdmin:list__action_draft.html.twig';
    } else {
        $actions['publish']['template'] = 'AppBundle:ArticleAdmin:list__action_preview.html.twig';
    }

    $listMapper->add('_actions', null, array('actions' => $actions));
}

But $this->getSubjet() always returns NULL. I also tried $listMapper->getAdmin()->getSubject() and many other getters but always the same result.

What am I doing wrong ?

Thanks for reading & have a good day :)


回答1:


You can do the check directly in the _action template, as you can access the current subject.

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('title')
        ->add('_action', 'actions', array(
            'actions' => array(
            'delete'  => array(),
            'preview' => array(
                'template' => 'AppBundle:ArticleAdmin:list__action_preview.html.twig',
            ),
            'draft'  => array(
                'template' => 'AppBundle:ArticleAdmin:list__action_draft.html.twig',
            ),
            'publish'  => array(
                'template' => 'AppBundle:ArticleAdmin:list__action_publish.html.twig',
            ),
        ))
    ;
}

And for example in AppBundle:ArticleAdmin:list__action_draft.html.twig, you can check your condition :

{% if object.isPublished %}
    your html code
{% endif %}


来源:https://stackoverflow.com/questions/40992129/how-to-retrieve-subject-in-sonata-configurelistfields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!