Search code examples
phpsymfonysonata-adminsymfony-sonata

Removing Add new (create) button for specific route


I˙m ṫrying to remove Add new button for /stageserver/list route.

I have tried with this code:

public function getBatchActions()
{
    $actions = parent::getBatchActions();

    if($this->hasRoute('/stageserver/list'))
    {
        $actions['remove'] = 'create';
    }

}

I have tried this next code, but it removes that route in all other admin sections.

public function configureRoutes(RouteCollection $collection)
{
   $collection->remove('create');
}

I can˙t find for specific route removal in Sonata docs, or perhaps I have missed it.


Solution

  • With Sonata, your Admin is related to a single entity.

    Example, I have an entity named AppBundle\Entity\StageServer.

    I create an Admin service to manage this entity :

    admin.stage_server:
        class: AppBundle\Admin\StageServerAdmin
        public: true
        arguments: [~, AppBundle\Entity\StageServer, ~]
        tags:
            - { name: sonata.admin, manager_type: orm }
    

    And a dedicated class for this service :

    <?php
    
    namespace AppBundle\Admin;
    
    use Sonata\AdminBundle\Admin\AbstractAdmin;
    use Sonata\AdminBundle\Route\RouteCollection;
    
    class StageServerAdmin extends AbstractAdmin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            $collection->remove('create');
        }
    }
    

    This should be enough to remove the ability to create AppBundle\Entity\StageServer objects.


    edit

    Solution using configureActionButtons method to remove create button only when onto the list action.

    <?php
    
    namespace AppBundle\Admin;
    
    use Sonata\AdminBundle\Admin\AbstractAdmin;
    use Sonata\AdminBundle\Route\RouteCollection;
    
    class StageServerAdmin extends AbstractAdmin
    {
        public function configureActionButtons($action, $object = null)
        {
            $buttons = parent::configureActionButtons($action, $object);
            if (in_array($action, array('list'))) {
                unset($buttons['create']);
            }
    
            return $buttons;
        }
    }