问题描述
是否有正确的方法来根据请求它的用户的角色自定义表单?
我的场景非常简单:如果用户没有授予 ROLE_ADMIN
权限,我需要隐藏一些字段.我试图避免 Twig 上的字段显示,但是
My scenario is pretty simple: I need to hide some fields if the user has not the ROLE_ADMIN
granted. I tried to avoid the field display on Twig, but
{% if is_granted('ROLE_ADMIN') %}
{{form_row(form.field)}}
{% endif %}
不起作用,因为表单构建器绕过了这个检查.
not works, because the form builder bypass this check.
Symfony 版本:2.8.2
Symfony version: 2.8.2
编辑
感谢@Rooneyl 建议,我找到了解决方案:
Thanks to the @Rooneyl suggestion I've found the solution:
首先,您需要将 'role' 键添加到 options 参数中.因此,在 configureOptions() $options['role']
中总是 ROLE_USER.
At first, you need to add the 'role' key to the options parameter. So, in the configureOptions() $options['role']
is always ROLE_USER.
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Ticket',
'role' => 'ROLE_USER'
));
}
然后在控制器中你必须传递 getRoles()
数组:
Then in the controller you have to pass the getRoles()
array:
$user_roles = $this->getUser()->getRoles();
$form = $this->createForm('MyBundle\Form\TicketType', $ticket, array('role' => $user_roles));
推荐答案
您可以使用传递给表单构建器的选项来说明生成了哪些元素.
通过这种方式,您可以更改已完成的内容和验证(使用 validation_groups).
例如,您的控制器(假设角色是一个数组);
您的控制器;
You could use an option passed to the form builder to say what elements are generated.
This way you can change the content and validation that gets done (using validation_groups).
For example, your controller (assuming roles is an array);
you controller;
$form = $this->createForm(new MyType(), $user, ['role' => $this->getUser()->getRoles()]);
还有你的表格:
<?php
namespace AppBundle\Form\Entity;
use AppBundle\Entity\UserRepository;
use Symfony\Component\Form\AbstractType,
Symfony\Component\Form\FormBuilderInterface,
Symfony\Component\OptionsResolver\OptionsResolver;
class MyType extends AbstractType
{
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
'validation_groups' => ['create'],
'role' => ['ROLE_USER']
));
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// dump($options['roles']);
if (in_array('ROLE_ADMIN', $options['role'])) {
// do as you want if admin
$builder
->add('name', 'text');
} else {
$builder
->add('supername', 'text');
}
}
/**
* @return string
*/
public function getName()
{
return 'appbundle_my_form';
}
}
这篇关于如何根据Symfony2/3中的用户角色自定义表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!