当用户具有特定的用户角色时,我需要修改表单字段属性以将其禁用。
我看到一个问题,提问者做了类似的事情:
->add('description')
if($user.hasRole(ROLE_SUPERADMIN))
->add('createdAt')
这对我来说就足够了,因为我只需要在整个Type中做一次,但我不能在表单生成器中使用if语句。当用户具有特定的用户角色时,是否有办法修改属性?
我想修改的部分是cashbackThreshold字段。此外,这是连续形式类型的一部分,我不能把它放在不同的形式类型中
//Payments panel
$builder->create('payments', 'form', array('virtual' => true, 'attr' => array('class' => 'form-section')))
->add('commission', 'integer')
->add('cashbackThreshold', 'integer')
编辑
我已经找到了做这件事的方法。
在我的类型中,我有:
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
....
public function buildForm(FormBuilderInterface $builder, array $options)
{
$disabled = false;
if(false === $this->securityContext->isGranted('ROLE_SUPER_ADMIN')) {
$disabled = true;
}
....
$builder->create('payments', 'form', array('virtual' => true, 'attr' => array('class' => 'form-section')))
->add('commission', 'integer')
->add('cashbackThreshold', 'integer', array(
'disabled' => $disabled
))
在我的控制器中,我有:
$form = $this->createForm(new WhiteLabelType($this->get('security.context')), $whiteLabel);
当然,您可以在FormType:中使用If条件
if($this->user.hasRole(ROLE_SUPERADMIN)) {
$builder->add('createdAt')
}
但是您需要在FormType控制器中注入$user,或者只注入您想要检查的布尔值,例如:
private $user;
public function __construct($user) {
$this->user = $user;
}
在控制器中,当您实例化FormType时,不要忘记添加它:
$user = $this->get('security.context')->getToken()->getUser();
$form = $this->createForm ( new yourFormType($user) // .... )
这当然不是推荐的方法。我只是想帮助你实现你想要做的事情。