FosUser如果thegrant是ADMIN,我如何添加角色字段

时间:2018-04-26 10:54:15

标签: symfony fosuserbundle

如果授权是admin和简单用户,我想在角色字段中显示differante值。

如果授权是role_admin,我将在角色字段User和admin中看到 如果是role_user我将拥有juste用户。

我使用的是FOSuser,这是我的UserType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name')
        ->add('surname')
        ->add('email')
        ->add('mobile')
        ->add('roles', ChoiceType::class, array(
            'choices' => array(
                'ADMIN' => 'ROLE_ADMIN',
                'SIMPLE USER' => 'ROLE_USER'),
            'multiple'=>true
        ));
}/**
 * {@inheritdoc}
 */

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

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\User'
    ));
}

1 个答案:

答案 0 :(得分:0)

将当前用户作为表单的选项。然后迭代$user->getRoles()以生成您的选择。

就像这样:

use AppBundle\Entity\User;
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $user = $options['user'];
    $builder->add('name')
        ->add('surname')
        ->add('email')
        ->add('mobile');
    if($user instanceof User){
        $choices = [];
        foreach($user->getRoles() as $key => $role){
            /* Do your key transform process here */
            $choices[$key] = $role;
        }
        $builder->add('roles', ChoiceType::class, array(
            'choices' => $choices,
            'multiple'=>true
        ));
    }
}/**
 * {@inheritdoc}
 */

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

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\User',
        'user'       => null
    ));
}

然后在表单init上传递当前用户。