Reputation: 41
hello everyone im new on symfony and been a little stuck trying to create an user with his respective role, everytime i try to add one i get this error: The property "roles" in class "...\Entity\Usuarios" can be defined with the methods "addRole()", "removeRole()" but the new value must be an array and or an instace of \Traversable, "...\Entity\Roles" given.
the roles in my db are ROLE_ADMIN and ROLE_USER, thats all good but cant register an user with his role in the form.
this is my Usuarios.php
<?php
namespace Paginas\UsuariosBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Usuarios
*
* @ORM\Table(name="usuarios")
* @ORM\Entity(repositoryClass="Paginas\UsuariosBundle\Repository\UsuariosRepository")
*/
class Usuarios implements AdvancedUserInterface, \Serializable
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=200)
*/
private $nombre;
/**
* @var string
*
* @ORM\Column(name="direccion", type="string", length=255)
*/
private $direccion;
/**
* @var \DateTime
*
* @ORM\Column(name="fechaNac", type="date")
*/
private $fechaNac;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=25)
*/
private $username;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=32)
*/
private $salt;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=64)
*/
private $password;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=30)
*/
private $email;
/**
* @var bool
*
* @ORM\Column(name="estado", type="boolean")
*/
private $estado;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return Usuarios
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set direccion
*
* @param string $direccion
* @return Usuarios
*/
public function setDireccion($direccion)
{
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* @return string
*/
public function getDireccion()
{
return $this->direccion;
}
/**
* Set fechaNac
*
* @param \DateTime $fechaNac
* @return Usuarios
*/
public function setFechaNac($fechaNac)
{
$this->fechaNac = $fechaNac;
return $this;
}
/**
* Get fechaNac
*
* @return \DateTime
*/
public function getFechaNac()
{
return $this->fechaNac;
}
/**
* Set username
*
* @param string $username
* @return Usuarios
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set salt
*
* @param string $salt
* @return Usuarios
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* @return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set password
*
* @param string $password
* @return Usuarios
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set email
*
* @param string $email
* @return Usuarios
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set estado
*
* @param boolean $estado
* @return Usuarios
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* @return boolean
*/
public function getEstado()
{
return $this->estado;
}
/**
* @ORM\ManyToMany(targetEntity="Roles", inversedBy="users", cascade={"all"});
*
*/
private $roles;
public function __construc(){
$this->roles = new ArrayCollection();
}
/**
* Add roles
*
* @param \Paginas\UsuariosBundle\Entity\Roles $roles
* @return Usuarios
*/
public function addRole(\Paginas\UsuariosBundle\Entity\Roles $roles)
{
$this->roles[] = $roles;
}
/**
* Remove roles
*
* @param \Paginas\UsuariosBundle\Entity\Roles $roles
*/
public function removeRole(\Paginas\UsuariosBundle\Entity\Roles $roles)
{
$this->roles->removeElement($roles);
}
/**
* Get roles
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
//return $this->roles->toArray();
//return array('ROLE_ADMIN');
//return array($this->roles);
}
/**
* @inheritDoc
*/
public function eraseCredentials(){
}
/**
* @see \Serializable::serialize()
*/
public function serialize(){
return serialize(array(
$this->id,
));
}
/**
* @see \Serializable::unserialize()
*/
public function unserialize($serialized){
list(
$this->id,
) = unserialize($serialized);
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->estado;
}
}
this is my Roles.php
<?php
namespace Paginas\UsuariosBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Roles
*
* @ORM\Table(name="roles")
* @ORM\Entity(repositoryClass="Paginas\UsuariosBundle\Repository\RolesRepository")
*/
class Roles implements RoleInterface
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=50)
*/
private $nombre;
/**
* @var string
*
* @ORM\Column(name="role", type="string", length=25)
*/
private $role;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return Roles
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set role
*
* @param string $role
* @return Roles
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* @return string
*/
public function getRole()
{
return $this->role;
}
/**
* @ORM\ManyToMany(targetEntity="Usuarios", mappedBy="roles");
*
*/
private $users;
public function __construc(){
$this->users = new ArrayCollection();
}
/**
* Add users
*
* @param \Paginas\UsuariosBundle\Entity\Usuarios $users
* @return Roles
*/
public function addUser(\Paginas\UsuariosBundle\Entity\Usuarios $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* @param \Paginas\UsuariosBundle\Entity\Usuarios $users
*/
public function removeUser(\Paginas\UsuariosBundle\Entity\Usuarios $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
UsuariosType.php
<?php
namespace Paginas\UsuariosBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Paginas\UsuariosBundle\Entity\Roles;
use Paginas\UsuariosBundle\Form\RolesType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class UsuariosType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nombre')
->add('direccion')
->add('fechaNac', 'date', array(
'label' => 'FechaNacimiento',
'format' =>'dd MM yyyy',
'years' =>range(date('Y')-50,date('Y')-17),
'required'=>true))
->add('username')
->add('password', PasswordType::class, array(
'label'=>'Contraseña'))
->add('email')
->add('estado', CheckboxType::class, array(
'label'=>'Activo',
'required'=>false,))
->add('roles', EntityType::class, array(
'class'=> 'PaginasUsuariosBundle:Roles',
'choice_label'=>'nombre',));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Paginas\UsuariosBundle\Entity\Usuarios'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'paginas_usuariosbundle_usuarios';
}
}
and my Controller.php
public function agregarAction()
{
$usuario=new Usuarios();
$form=$this->createForm(new UsuariosType(), $usuario);
$request = $this->getRequest();
if($request->getMethod() == 'POST')
{
$form->bind($this->getRequest());
if($form->isValid())
{
$usuario=$form->getData();
$cadena_salt = md5(uniqid(null, true));
$usuario->setSalt($cadena_salt);
$em=$this->getDoctrine()->getManager();
$em->persist($usuario);
$em->flush();
$em=$this->getDoctrine()->getManager();
$product=$em->getRepository('PaginasUsuariosBundle:Usuarios')->findALl();
return $this->redirectToRoute('usuario_lista');
}
}
return $this->render('PaginasUsuariosBundle:Default:crear_usuario.html.twig',
array('form' => $form->createView()
));
dont know what to do, could someone help me please
Upvotes: 1
Views: 11008
Reputation: 1532
Define your roles in the /app/config/security.yml also if you need you can add more roles like 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]
If you need to get roles in your Controller
$roles = $this->getParameter('security.role_hierarchy.roles');
If you need to get roles into FormType
$roles = $this->getParent('security.role_hierarchy.roles');
and in the form,(note this is one example for multi select you can change this as dropdown, checkbox or as you want)
->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,
)
)
Upvotes: 3
Reputation: 2358
You need to pass array of roles instead of roles
object. Use 'multiple' => true
in form builder with 'roles`.
UsuariosType.php
->add('roles', EntityType::class, array(
'class'=> 'PaginasUsuariosBundle:Roles',
'multiple' => true, // Allow multiple selection
'choice_label'=>'nombre')
);
Upvotes: 1