Kable
Kable

Reputation: 117

Symfony 2 get defined roles in a custom form field type

In my project I want the admins to be able to change the required role to see certain content using a choice field. I have an ArticleType that builds the form for me:

class ArticleType extends AbstractType
{   
    ...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title')
                ->add('requiredRole', 'choice');

    }

    ...
}

I also want to to translate the roles. For example 'ROLE_ADMIN' is translated as 'Admins'. Since I need this function in some different forms too, I thought creating a custom form field type would be a good solution.

But then I have the problem that I can't access the defined roles.

I got it to work without a custom field type with this in the controller

$form = $this->createForm(new ArticleType($this->container->getParameter('security.role_hierarchy.roles')), $article);

and this in the ArticleType

class ArticleType extends AbstractType
{   
    ...

    private $roles;

    public function __contruct($roles)
    {
        $this->roles = $this->refactorRoles($roles);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title')
                ->add('requiredRole', 'choice', array('choices' => $this->roles);

    }

    ...
}

But with this solution I have to include the refactorRoles function in every Type i need the roles field in and when I add or rename a role I have to change every Type again.

So my question is, how can I create a custom roleType can access the defined roles and translate them? Also, is this a good idea or should I do something different?

Upvotes: 0

Views: 389

Answers (1)

Tom Tom
Tom Tom

Reputation: 3698

Well you don't necessarily need to do this. The better practice would probably be to create a Role entity add your corresponding roles' front-end name (Admin) and back-end value (ROLE_ADMIN) and create a One-To-Many association to the Article entity. You can then use the entity field (= choice field of entities) directly in the builder of your form's type file and you can specify which property should be shown (you'd want the front-end name). To show an article you will need to query join those tables and from there check the user's role to the article minimum role's back-end value.

One of the advantages of the Doctrine ORM is to make those kind of things trivial once you get used to it.

Upvotes: 2

Related Questions