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

后端 未结 2 1909
执念已碎
执念已碎 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 08:39

    You can do it in your form.

    Make a service for your form

    app.form.type.task:
        class: AppBundle\Form\FormType
        arguments: ["@security.authorization_checker"]
        tags:
            - { name: form.type }
    

    In your FormType, add a constructor to get your service.

    private $authorization;
    public function __construct(AuthorizationChecker $authorizationChecker)
    {
        $this->authorization = $authorizationChecker;
    }
    

    Then, in your builder, you will be able to check user permission

    $builder->add('foo');
    if($this->authorization->isGranted('ROLE_ADMIN'))
    {
       $builder->add('bar');
    }
    

    And then, finally, you can render your form

    {% if form.formbar is defined %}
        {{ form_row(form.formbar ) }}
    {% endif %}
    

    Please note that it mean that your field may be null. Because maybe you want to see some of them visible by some users and others not.

    Else, you can set a default value in your entity construct method, to make sure value won't be null if user don't/can't fill it.

提交回复
热议问题