我如何在 Symfony2 的 Form Builder 类中访问用户角色 [英] How can i access the user Role in Form Builder class in Symfony2
问题描述
我的表单为 UserType
和这样的字段
I have the form as UserType
with field like this
->add('description')
->add('createdAt')
现在我希望如果登录用户具有角色 (ROLE_SUPERADMIN)
那么他可以看到这样的额外字段
Now i want that if the Logged in user has Role (ROLE_SUPERADMIN)
then he can see extra fields like this
->add('description')
if($user.hasRole(ROLE_SUPERADMIN))
->add('createdAt')
实际上我必须为许多领域这样做.有什么办法可以制作一些自定义类型,这样如果有那种类型,那么只有管理员才能看到那些像
Actually i have to do that for many fields . is there any way i can make some custom type so that if that type is there then only admin can see those like
->add('createdAt',"MyCustomType")
推荐答案
非常简单.只需根据安全上下文将您的自定义表单类型设为服务即可:
Pretty simple. Just make your custom form type a service, depending on the security context:
use SymfonyComponentSecurityCoreSecurityContext;
class UserType extends AbstractType
{
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function buildForm(FormBuilder $builder, array $options)
{
// Current logged user
$user = $this->securityContext->getToken()->getUser();
// Add fields to the builder
}
public function getDefaultOptions(array $options)
{
return array(
'required' => false,
'data_class' => 'AcmeHelloBundleEntityUser'
);
}
public function getName()
{
return 'user_type';
}
}
然后将类标记为服务,使用特殊标签form.type
:
Then mark the class as a service, with the special tag form.type
:
services:
form.type.user:
class: AcmeHelloBundleFormTypeUserType
arguments: ["@security.context"]
tags:
- { name: form.type, alias: user_type }
在您的控制器中,不要执行 new UserType()
,而是从容器中获取服务:
In your controller, instead of doing new UserType()
, grap the service from the container:
$form = $this->createForm($this->get('form.type.user'), $data);
这篇关于我如何在 Symfony2 的 Form Builder 类中访问用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!