FOSUserBundle在编辑视图中显示组角色

时间:2013-11-15 17:25:36

标签: symfony edit fosuserbundle role

我正在尝试重写控制器和formtype,以在我的视图中显示所选组中的角色,但我找不到正确的方法。我已经按照步骤覆盖了一切,这是有效的,但当我试图向服务说我正在向构造函数传递一个实体对象时出现了问题。

由于必须覆盖formtype,如何传递您需要实现的服务,我的Group实体?

有没有人知道如何实现这个目标?

这就是我所做的:

  1. 覆盖控制器,在创建表单时,传递$group实体

    $formFactory = $this->container->get('fos_user.group.form.factory');
    $form = $formFactory->createForm($group);  //Here
    
  2. 覆盖表单,并使用自定义__construct方法,我可以传递我的实体(也许这是我的错误,应该以更好或其他方式完成)

    public function __construct(Container $container, Groups $group)
    {
        $this->container = $container;
        $this->roles = array_keys($this->container->getParameter('security.role_hierarchy.roles'));
    
        $this->group = $group; #How? 
    }
    
  3. 获取角色密钥的容器没有错误地传递,这有效。

    1. 按照文档说明创建服务(这是真正的问题和例外)

       x_s_cosmos.group.form.type:
          class: X\S\CosmosBundle\Form\Type\GroupFormType
          arguments: [@service_container, here_should_be_my_entity?]
          tags:
              - { name: form.type, alias: kosmos_group_form }
      
    2. 我真的很满意,并且不知道如何继续下去。

2 个答案:

答案 0 :(得分:4)

最后,在覆盖GroupController.php并向我的表单添加选择字段类型后,我可以实现我的目标。

    $form->add('roles', 'choice', array(
                'choices' => $this->getExistingRoles(),
                'data' => $group->getRoles(),
                'label' => 'Roles',
                'expanded' => true,
                'multiple' => true,
                'mapped' => true,
            ));

getExistingRoles()的位置是:

    $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
    $roles = array_keys($roleHierarchy); 

    foreach ($roles as $role) {
        $theRoles[$role] = $role;
    }
    return $theRoles;

我只是走错了方向,获取组的角色并在管理界面中显示它们并不困难,这样您就可以选择一个系统角色并将其提供给组。无需覆盖FormType,只需要控制器将自己的字段添加到表单中。

希望它有所帮助,因为它给我带来了很多麻烦。

答案 1 :(得分:1)

您不应该将实体传递给构造函数。如果需要访问表单中的实体,则必须向表单构建器添加事件侦听器,如下所示:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $form   = $event->getForm();
        $entity = $event->getData(); 

        // This is your Group entity, now do something with it...
        if ($entity instanceof Group) {
            // $form->add ...
        }
    });
}
相关问题