Search code examples
phpsymfonybundlefosuserbundle

How to create 3 roles with 3 entities?


I'm developing a web application now, i want create 3 roles for 3 entities (Student, teacher, School).

When the user click on inscription he is redirected to a first step he can choose between 3 choices (3 radios boxes) student, teacher or school, after the confirmation he is redirected to another page that contain a form with diferents inputs depending on the first step.

How to do that with Symfony 3? Can I do that with ForUserBundle?


Solution

  • In the controller of the first step decide where to redirect based on the radio value :

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        if( studentRadio is selected ){
            $this->render("student.html.twig")
        } else if (...) {
            ...
        }
        ....
    }
    

    FOSUserBundle makes it easy to add roles because the BaseUser class has a method to add roles : $user->addRole("ROLE_STUDENT");

    Role name must begin with ROLE_ and must be all uppercase and you can create as many as you want

    EDIT :

    Roles are just string values that are stored within a $roles field within your User class then you can require a certain role to access certain pages in the security.yml file, when you want to acces a page that requires a role, symfony will check that field to see if the user has the required role

    You can create three classes : Student, Teacher and School and have each one of them have a field named $account wich is the default User class from FOSUserBundle and link them with @ORM\OneToOne association and add AccountType in the FormType of those 3 classes, this way in the database each class has a table for it and each object of those class is linked to an account and all accounts are stored in one table

    In the first step make the user choose a role, then the website directs him to either Student registration, Teacher registration or School registration depending on what he chose, in their controllers don't forget to use ->addRole("your role"), example : $student->getAccount->addRole("ROLE_STUDENT");

    I had a project that i worked on where i have a Person entity with Account entity (which is the default FOSUserBundle User class), the registration was done by PersonType and not by AccountType because i couldn't add the roles i wanted after the default FOSUserBundle's registration form was submitted (i didn't want to modify the FOSUserBundle's controller that handles registration for simplicity reasons)

    check out this question i asked that talks about it : Symfony fosuserbundle add Account entity to a person entity

    Associations are explained here : http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

    Roles are explained here : http://symfony.com/doc/current/security.html