如何检查Symfony2中表单构建器中的用户角色? [英] how to check the user role inside form builder in Symfony2?

查看:35
本文介绍了如何检查Symfony2中表单构建器中的用户角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在尝试检查用户是否具有特定角色,我做到了 这个

Okay, i'm trying to check if an user has a specific role, i did this

但是,当我这样做时:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
        ->add('nombre',null,array('label' => 'Usuario'))
        ->add('email')
        ->add('password', 'repeated', array(
            'type' => 'password',
            'invalid_message' => 'Los campos deben coincidir',
            'first_name' => 'password',
            'second_name' => 'confirmar password',
            'options' => array('required' => false)
            ))

        ->add('cliente', 'entity', array(
        'class' => 'ClientesBundle:Cliente',
        'empty_value' => 'Company',            
        'required'    => false,
        'empty_data'  => null)
    **)**
      $user = $this->securityContext->getToken()->getUser();
      **if ($user->getRol() == 'ROLE_SUPER_ADMIN'){**
        ->add('rol') 
        **}**
    ;

}

也试过了:

 **if ($this->securityContext->getToken()->getUser()->getRol() === 'ROLE_SUPER_ADMIN'){**
            ->add('rol') 
            **}**

粗体线(带有 ** 的线)有一条细小的红线,表示有错误,如果...我该如何解决这个问题?

the bolded lines (the ones with **) have the tiny red line that indicates an error, and it's says unexpected if... How do i fix this?

推荐答案

从控制器你必须将用户对象传递给表单生成器

From controller you have to pass user object to form builder

$form = $this->createForm(
    new YourType(), 
    $data, 
    array('user' => $this->getUser())
);

然后在表单生成器中,您可以从 $options 中获取它:

Then in form builder you can fetch it from $options:

public function buildForm(FormBuilder $builder, array $options)
{
    $user = $options['user']
}

不要忘记使用 user 索引扩展 setDefaultOptions():

Don't forget to extend setDefaultOptions() with user index:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        ...
        'user' => null
    ));
}

这篇关于如何检查Symfony2中表单构建器中的用户角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆