将角色字段添加到FOSUserBundle组表单

时间:2015-02-10 18:52:26

标签: symfony fosuserbundle

在FOSUserBundle中激活组(基于其documentation时)时,组角色未嵌入编辑和更新表单中!我已经覆盖了GroupFormType和GroupController但我无法将角色从控制器传递到表单类。 我的问题是如何在表单中添加角色以让管理员更改或为组分配角色?

2 个答案:

答案 0 :(得分:4)

通过添加角色字段来覆盖我的问题来覆盖GroupController

public function editAction(Request $request, $groupName)
{
   ...

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.group.form.factory');

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

  ...
}
public function getExistingRoles()
{
    $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
    $roles = array_keys($roleHierarchy);

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

答案 1 :(得分:0)

就我而言,我决定编写GroupFormType类。这是继承的类:

namespace UserBundle\Form;

use FOS\UserBundle\Form\Type\GroupFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;

class GroupType extends AbstractType
{
/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $permissions = array(
        'Utilisateur'        => 'ROLE_USER',
        'Administrateur'     => 'ROLE_ADMIN'
    );

    $builder
        ->add('name', null, array('label' => 'form.group_name', 'translation_domain' => 'FOSUserBundle'))
        ->add('role', ChoiceType::class, array(
            'label'   => 'Rôle',
            'choices' => $permissions,
            'multiple' => true,
            'expanded' => true
        ))
    ;
}

public function getParent()
{
    return GroupFormType::class;
}
}

不要忘记在config.yml

中准确掌握新课程
fos_user:
    group:
        form:
            type: UserBundle\Form\GroupType