Search code examples
symfonyeasyadmin

How to add item_permission on delete action in easyadmin?


I use EasyadminBundle for the Backend of a Symfony application.

Two type of users have access to the back-end and I'd like to keep the right to delete to a small number of persons granted with ROLE_ADMIN.
I'd like to use item_permission parameter as for the other actions (such as show or list) :

Lieu:
    class: App\Entity\Lieu
    list:
        item_permission: ROLE_ENCADRANT
    delete:
        item_permission: ROLE_ADMIN

But it's not working and I can still delete user when I'm logged with ROLE_ENCADRANT. Is there another solution ?

I currently accomplish it with:

Lieu:
    class: App\Entity\Lieu
    list:
        item_permission: ROLE_ENCADRANT
        action: ['-delete']
        help: "the delete button is accessible in <b>Edit</b> view"
    form:
        item_permission: ROLE_ADMIN

I'm just looking for a 100% configuration solution, more elegant than mine.


Solution

  • Take a look at adding an action in the docs. The action can be tied to a route, which allows specifying what role may perform the action. The downside is that the list view button is present regardless of role. You can add a flash message to advise the user whether they have permission.

    Here's an example from a project. Not quite what you're looking for but may get you started:

    easyadmin.yaml:

    Admin:
        class: App\Entity\Admin
        disabled_actions: ['new', 'edit']
        list:
            actions:
                -
                    name: 'admin_enabler'
                    type: 'route'
                    label: 'Enable/Disable'
    

    controller:

        /**
         * @Route("/enabler", name = "admin_enabler")
         */
        public function enabler(Request $request)
        {
            $em = $this->getDoctrine()->getManager();
            $id = $request->query->get('id');
            $admin = $em->getRepository(Admin::class)->find($id);
            $enabled = $admin->isEnabled();
            if (!$admin->isActivator() && !$admin->hasRole('ROLE_SUPER_ADMIN')) {
                $admin->setEnabled(!$enabled);
                $em->persist($admin);
                $em->flush();
            } else {
                $this->addFlash('danger', $admin->getFullName() . ' cannot be disabled');
            }
    
            return $this->redirectToRoute('easyadmin', array(
                'action' => 'list',
                'entity' => $request->query->get('entity'),
            ));    
        }