我在symfony的第二天:-)我创建了实体,表单和控制器“REGISTER USER”。我的表单将用户添加到数据库,但不添加其角色。
我在此页面上建模:http://symfony.com/doc/current/cookbook/security/entity_provider.html
数据库角色:
ID | NAME | ROLE
1 | user | ROLE_USER
2 | admin | ROLE_ADMIN
DB user_role
USER_ID | ROLE_ID
(EMPTY)
这是我的代码:
用户
class User implements UserInterface, \Serializable {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//other fields
/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
//....
public function getRoles()
{
return $this->roles->toArray();
}
//....
}
作用
class Role implements RoleInterface{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* @ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* @see RoleInterface
*/
public function getRole()
{
return $this->role;
}
}
一段代码控制器
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new RegisterType);
$form->handleRequest($Request);
if($form->isValid()){
$formData=$form->getData();
if($formData['password']==$formData['repeatpassword']){
$factory = $this->get('security.encoder_factory');
$user = new User();
$encoder = $factory->getEncoder($user);
$user->setSalt(md5(time()));
$pass = $encoder->encodePassword($formData['password'], $user->getSalt());
$user->setEmail($formData['email']);
$user->setPassword($pass);
$user->setActive(1);
$user->setName($formData['name']);
$user->setSurname($formData['surname']);
$user->setCountry($formData['country']);
$user->setBirthdate($formData['birthdate']);
$user->setCity($formData['city']);
$user->setBirthdate($formData['birthdate']);
$user->setAddress($formData['address']);
$user->setPhone($formData['phone']);
$user->setZipcode($formData['zipcode']);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
}
如何向用户添加角色?我想在参数中给出角色的id或名称。
答案 0 :(得分:0)
你有一个良好的开端,但这是你需要知道/做的下一步:
This documentation将向您展示如何从数据库中获取实体。 This documentation将向您展示如何保存相关实体。
$user->setSalt(md5(time()));
不安全;你应该参考
this documentation了解如何以安全的方式正确生成密码。
您不应该手动绑定每个字段,而应该遵循this documentation以了解如何正确处理表单,并this documentation知道如何将实体绑定到FormType类。