如何使用表单symfony向用户添加角色

时间:2017-01-03 20:52:36

标签: php symfony

大家好我是symfony的新手,并且尝试创建一个具有各自角色的用户时有点困难,每次我尝试添加一个我都会收到此错误:类中的“角色”属性“... \ Entity \ Usuarios“可以使用方法”addRole()“,”removeRole()“定义,但新值必须是\ Traversable的数组和/或实例,”... \ Entity \ Roles“。

我的数据库中的角色是ROLE_ADMIN和ROLE_USER,这些都很好但是无法在表单中注册用户。

这是我的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;
}

}

这是我的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';
}


}

和我的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()
));

不知道该怎么做,有人可以帮我吗

2 个答案:

答案 0 :(得分:1)

您需要传递角色数组而不是roles个对象。在表单构建器中使用'multiple' => true和#39; roles`。

<强> UsuariosType.php

->add('roles', EntityType::class, array(
    'class'=> 'PaginasUsuariosBundle:Roles',
    'multiple' => true, // Allow multiple selection
    'choice_label'=>'nombre')
);

答案 1 :(得分:1)

如果需要,还可以在/app/config/security.yml中定义您的角色,可以添加更多角色,如下所示

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]

如果您需要在Controller中获得角色

$roles = $this->getParameter('security.role_hierarchy.roles');

如果您需要将角色转换为FormType

$roles = $this->getParent('security.role_hierarchy.roles');

并在表单中,(注意这是多选的一个示例,您可以将其更改为下拉列表,复选框或根据需要)

->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,
    )
)