Search code examples
symfonysonata-admin

How to retrieve subject in Sonata configureListFields?


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 :)


Solution

  • 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 %}