I have the form as UserType
with field like this
我有像UserType这样的表单
->add('description')
->add('createdAt')
Now i want that if the Logged in user has Role (ROLE_SUPERADMIN)
then he can see extra fields like this
现在我希望如果登录用户有角色(ROLE_SUPERADMIN),那么他可以看到这样的额外字段
->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")
- >加( 'createdAt', “MyCustomType”)
1 个解决方案
#1
26
Pretty simple. Just make your custom form type a service, depending on the security context:
很简单。只需使您的自定义表单键入服务,具体取决于安全上下文:
use Symfony\Component\Security\Core\SecurityContext;
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' => 'Acme\HelloBundle\Entity\User'
);
}
public function getName()
{
return 'user_type';
}
}
Then mark the class as a service, with the special tag form.type
:
然后使用特殊标记form.type将该类标记为服务:
services:
form.type.user:
class: Acme\HelloBundle\Form\Type\UserType
arguments: ["@security.context"]
tags:
- { name: form.type, alias: user_type }
In your controller, instead of doing new UserType()
, grap the service from the container:
在您的控制器中,而不是执行新的UserType(),从容器中抓取服务:
$form = $this->createForm($this->get('form.type.user'), $data);
#1
26
Pretty simple. Just make your custom form type a service, depending on the security context:
很简单。只需使您的自定义表单键入服务,具体取决于安全上下文:
use Symfony\Component\Security\Core\SecurityContext;
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' => 'Acme\HelloBundle\Entity\User'
);
}
public function getName()
{
return 'user_type';
}
}
Then mark the class as a service, with the special tag form.type
:
然后使用特殊标记form.type将该类标记为服务:
services:
form.type.user:
class: Acme\HelloBundle\Form\Type\UserType
arguments: ["@security.context"]
tags:
- { name: form.type, alias: user_type }
In your controller, instead of doing new UserType()
, grap the service from the container:
在您的控制器中,而不是执行新的UserType(),从容器中抓取服务:
$form = $this->createForm($this->get('form.type.user'), $data);