Zwen2012
Zwen2012

Reputation: 3498

Symfony: How to get the current User Role in a Formtype or security.authorization_checker

I have a Formtype and I need to get access to the current Useres ROLE because I want to decide, which fields are beeing shown. Is it possible to get access to the security.authorization_checker for example so that I can make an if clause:

if (!$this->get('security.authorization_checker')->isGranted('IS_ADMIN')) { ....

Upvotes: 1

Views: 2968

Answers (2)

Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10028

As mentioned above you can create your onw form based on this snipper of code I used in order to render a field at any NON-admin user:

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Validator\Constraints\IsTrue as TrueConstraint;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;

class RegistrationType extends AbstractType
{

    /**
    * @var AuthorizationChecker
    */
    private $authorizationChecker=null;

    public function __construct(AuthorizationChecker $authorizationChecker)
    {
      $this->authorizationChecker=$authorizationChecker;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name',TextType::class,["label"=>"register.name","required"=>true,'translation_domain' => 'FOSUserBundle'])
                ->add('surname',TextType::class,["label"=>"register.surname","required"=>true,'translation_domain' => 'FOSUserBundle']);

        if(!$this->authorizationChecker->isGranted('ROLE_ADMIN'))
        {
          $builder->add('accept_terms',CheckboxType::class,["label"=>"register.acceptTerms","required"=>true,'translation_domain' => 'FOSUserBundle',
                                                            'mapped' => false,'constraints' => new TrueConstraint(array('message' => 'Your Confirmation Message','groups' => 'Registration'))]);
        }
    }

   // Extra stuff ommited for convenience
}

So as you can see I use if a user is admin via $this->authorizationChecker->isGranted('ROLE_ADMIN') piece of code.

SO you just have to put the '@security.authorization_checker' as service argument.

Upvotes: 0

Maulik Savaliya
Maulik Savaliya

Reputation: 1260

You can register your form as service and then pass security.authorization_checker as arguments, Check below sample code.

form.service.id:
    class: YourFormClass
    arguments: ['@security.authorization_checker']
    tags:
        - { name: form.type }

Then in your form class create __construct(AuthorizationChecker $authorizationChecker) method and then use AuthorizationChecker to check ROLE

Upvotes: 5

Related Questions