我需要修改表单字段属性,以便在用户具有特定用户角色时禁用它。
我看到一个Question,其中提问者做了类似的事情:
->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);
答案 0 :(得分:0)
当然,您可以在FormType中使用If条件:
if($this->user.hasRole(ROLE_SUPERADMIN)) {
$builder->add('createdAt')
}
但是你需要在FormType Controller中注入$ user,或者只是想要检查这个布尔值,例如:
private $user;
public function __construct($user) {
$this->user = $user;
}
在实例化FormType时,在Controller中也不要忘记添加它:
$user = $this->get('security.context')->getToken()->getUser();
$form = $this->createForm ( new yourFormType($user) // .... )
这肯定不是推荐的方法。我只是想帮助你实现你想做的事。