How to customize form field based on user roles in Symfony2/3?

后端 未结 2 1895
执念已碎
执念已碎 2021-02-20 08:23

Is there a correct way to customize a form depending on the role of the user that requests it?

My scenario is pretty simple: I need to hide some fields

2条回答
  •  离开以前
    2021-02-20 09:00

    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()]);
    

    And your form:

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

提交回复
热议问题