'sonata-admin: creating a voter

I am using Symfony 4.4 and sonata-admin 3.107

I created a voter for one of my admin pages (SampleAdmin).

class SampleVoter extends Voter
{
   protected function supports($attribute, $subject): bool
    {
        return in_array($attribute, ['LIST', 'VIEW', 'CREATE', 'EDIT'])
            && $subject instanceof 'App\Entity\Sample';
    }
    
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if ($attribute === 'EDIT') {
            return false;
        }
        
        return true;
    }
}

And I registered it in my services:

App\Voter\SampleVoter:
   tags: [ security.voter ]

But it is not loaded when loading the sonata page in the browser. Should I do something more?



Solution 1:[1]

How do you know not loaded? Raise exception in supports() method:

class SampleVoter extends Voter
{
   protected function supports($attribute, $subject): bool
   {
       return in_array($attribute, ['LIST', 'VIEW', 'CREATE', 'EDIT']);
   }
    
   protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if ($attribute === 'EDIT') {
            return false;
        }
        
        return true;
    }
}

btw, No need to register in services.yaml, because of service auto wiring.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1