Add roles field to FOSUserBundle group form

冷暖自知 提交于 2020-01-06 02:30:10

问题


When activating group( base on its documentation) in FOSUserBundle, the group roles are not embedded on edit and update form!I already override GroupFormType and GroupController but I can't pass roles from controller to form class. my question is how can I add roles to form to let administrator change or assign role to groups?


回答1:


Solving my problem by adding the role field to override 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;
}



回答2:


For my part I decided to inerite the GroupFormType class. Here is inherited class :

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;
}
}

Don't forget to precise your new class in the config.yml

fos_user:
    group:
        form:
            type: UserBundle\Form\GroupType


来源:https://stackoverflow.com/questions/28439512/add-roles-field-to-fosuserbundle-group-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!