php - Symfony3 how to store user roles in database -
symfony version: 3.1.3 database: mysql
i have users table , has column roles(longtext-dc2type:array).
in controller have created dropdown box form bellow,
$user = new users; $form = $this->createformbuilder($user) // other fields ->add('roles', choicetype::class, array( 'attr' => array( 'class' => 'form-control', 'style' => 'margin:5px 0;'), 'choices' => array( 'teacher' => true, 'student' => true, 'parent' => true ), ) ) // other fields ->getform();
and getting user selected role bellow,(within same controller)
if( $form->issubmitted() && $form->isvalid() ){ // other codes $role = $form['roles']->getdata(); // other codes if( $role == 0 ){ $userrole = array ('teacher'); } elseif( $role == 1 ){ $userrole = array ('student'); } elseif( $role == 2 ){ $userrole = array ('parent'); } $user->addrole($userrole); $em = $this->getdoctrine()->getmanager(); $em->persist($user); $em->flush(); }
but gives me following error,
expected argument of type "array", "boolean" given
i think doing wrong way , know right way insert roles database.
here did rid issue,
define roles in /app/config/security.yml below,
role_hierarchy: role_admin: [role_admin] role_super_admin: [role_super_admin, role_allowed_to_switch] role_teacher: [role_teacher] role_student: [role_student] role_parent: [role_parent]
in controller, roles /app/config/security.yml using following code
$roles = $this->getparameter('security.role_hierarchy.roles');
and code roles in formtype,
$roles = $this->getparent('security.role_hierarchy.roles');
and in formtype, (here multi select)
->add('roles', choicetype::class, array( 'attr' => array('class' => 'form-control', 'style' => 'margin:5px 0;'), 'choices' => array ( 'role_admin' => array ( 'yes' => 'role_admin', ), 'role_teacher' => array ( 'yes' => 'role_teacher' ), 'role_student' => array ( 'yes' => 'role_student' ), 'role_parent' => array ( 'yes' => 'role_parent' ), ) , 'multiple' => true, 'required' => true, ) )
edit user roles has defined in /app/config/security.yml below
role_hierarchy: role_admin: [role_admin] role_super_admin: [role_super_admin, role_allowed_to_switch] role_teacher: [role_teacher] role_student: [role_student] role_parent: [role_parent]
Comments
Post a Comment