调用security.authorization_checker服务

时间:2017-05-31 17:18:07

标签: symfony

大家好,感谢你们。

我正在使用Symfony 3.0.2并且正在尝试获取服务security.authorization_checker的类,以便查看谁连接到我的应用程序的ROLE_ 但我有这个错误:

尝试调用类“AppBundle \ Form \ RegistrationType”的名为“get”的未定义方法。 你的意思是打电话,例如“getBlockPrefix”,“getName”或“getParent”?

class RegistrationType extends AbstractType  {



public function buildForm(FormBuilderInterface $builder, array $options){

    $roles = new LoadRoles();
   // $container = new Container();

  //  $this->denyAccessUnlessGranted('ROLE_ADMIN');
    //LOAD ROLES FOR SUPER ADMIN
    if($this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')){
            $roles->getRolesForAdmin($builder, $options);
    }

    //LOAD ROLES FOR ADMIN
    if($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
            $roles->getRolesForManager($builder, $options);
    }

    //LOAD ROLES FOR ASSOCIATION
    if($this->get('security.authorization_checker')->isGranted('ROLE_ASSOCIATION')){
        $roles->getRolesForAssociation($builder, $options);
    }

}

问题位于:$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN') 该函数无法识别get()函数,因为它不扩展Controller 我想知道是否有办法访问此服务?我是Symfony的新人,请原谅我的 诚恳

1 个答案:

答案 0 :(得分:1)

来自您的控制器:

$form = $this->createForm($form, $item, array(
    'authService' => $this->get('security.authorization_checker')
));

以您的形式:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver
        //..
        ->setRequired('authService')
    ;
}

您现在可以在buildForm函数中访问您的服务:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $authService = $options['authService'];
    //...
}