Php 如何访问Symfony2中Form Builder类中的用户角色

Php 如何访问Symfony2中Form Builder类中的用户角色,php,symfony,doctrine-orm,Php,Symfony,Doctrine Orm,我的表单为UserType,字段如下 ->add('description') ->add('createdAt') ->add('description') if($user.hasRole(ROLE_SUPERADMIN)) ->add('createdAt') 现在我想知道,如果登录用户有Role(Role\u SUPERADMIN),那么他可以看到这样的额外字段 ->add('description') ->add('createdAt'

我的表单为
UserType
,字段如下

->add('description')
  ->add('createdAt')
 ->add('description')
if($user.hasRole(ROLE_SUPERADMIN))
->add('createdAt')
现在我想知道,如果登录用户有Role
(Role\u SUPERADMIN)
,那么他可以看到这样的额外字段

->add('description')
  ->add('createdAt')
 ->add('description')
if($user.hasRole(ROLE_SUPERADMIN))
->add('createdAt')
事实上,我在很多领域都必须这样做。有没有办法我可以做一些自定义类型,这样,如果该类型存在,那么只有管理员可以看到类似的


->add('createdAt',“MyCustomType”)

非常简单。只需将自定义表单类型设置为服务,具体取决于安全上下文:

使用Symfony\Component\Security\Core\SecurityContext;
类UserType扩展了AbstractType
{
私人$securityContext;
公共函数构造(SecurityContext$SecurityContext)
{
$this->securityContext=$securityContext;
}
公共函数buildForm(FormBuilder$builder,数组$options)
{
//当前登录用户
$user=$this->securityContext->getToken()->getUser();
//向生成器添加字段
}
公共函数getDefaultOptions(数组$options)
{
返回数组(
“必需”=>false,
“数据\u类”=>“Acme\HelloBundle\Entity\User”
);
}
公共函数getName()
{
返回“用户类型”;
}
}
然后用特殊标记
表单将该类标记为服务。键入

服务:
form.type.user:
类:Acme\HelloBundle\Form\Type\UserType
参数:[“@security.context”]
标签:
-{name:form.type,别名:user\u type}
在控制器中,不要执行
new UserType()
,而是从容器中绘制服务:

$form=$this->createForm($this->get('form.type.user'),$data);
参数:[“@security.authorization\u checker”]在sf2.6之后