Symfony does not remove Element from ArrayCollection - symfony

i want to remove an role from the roles-ArrayCollection in the User Entity.
User and Role have an M:N connection.
In my Controller:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->find($userId);
$user->removeRole($roleID);
$em->flush();
If I execute the controller, there are no error messages.
But the Role is still assigned to the user.
User Entity
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="usermanagement_users")
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface,\Serializable
{
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
$this->isActive = true;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->roles->toArray();
}
public function setRoles($roles){
$this->roles[] = $roles;
}
public function removeRole($role){
unset($this->roles->toArray()[$role]);
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=60)
*/
private $vorname;
/**
* #ORM\Column(type="string", length=60)
*/
private $nachname;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $letzterLogin;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function setId($id){
$this->id = $id;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}
Role Entity
<?php
/**
* Created by PhpStorm.
* User: christianschade
* Date: 02.02.15
* Time: 19:29
*/
namespace Chris\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Role
* #ORM\Entity(repositoryClass="Chris\UserBundle\Entity\RoleRepository")
* #ORM\Table(name="usermanagement_roles")
*/
class Role implements RoleInterface {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
public function getRole() {
return $this->role;
}
/**
* #ORM\ManyToMany(targetEntity = "User", inversedBy = "roles")
*
* #var ArrayCollection $users
*/
protected $users;
/**
* #return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* #param ArrayCollection $users
*/
public function setUsers($users)
{
$this->users = $users;
}
public function setRoles($roles)
{
$this->role = $roles;
// allows for chaining
return $this;
}
/**
* #inheritDoc
*/
public function getId()
{
return $this->id;
}
/**
* #ORM\ManyToMany(targetEntity = "Chris\UserBundle\Entity\Group", inversedBy = "groups")
*
* #var ArrayCollection $group
*/
private $group;
/**
* #return ArrayCollection
*/
public function getGroup()
{
return $this->group;
}
/**
* #param ArrayCollection $group
*/
public function setGroup($group)
{
$this->group = $group;
}
}

You should use ArrayCollection::removeElement() to remove the role.
public function removeRole($role)
{
$this->roles->removeElement($role);
}
On a side note, I feel your getRoles() implementation is unorthodox as it would be recommended to return the ArrayCollection as is and call toArray() if you need to once you have retrieved it.
public function getRoles()
{
return $this->roles;
}

Related

Multiple joins in a ManyToMany relation

I have 3 entities, User, Parking and Voiture.
User had a ManyToMany relation with parking while Parking has a OneToMany reamtion with voiture.
what I'm trying to do:
Get the cars (voitures) that belong to all parkings the currect user is related to
how I'm trying to do it:
Using querybuilder, but I still don't know how to make it work
here are my entities
Entity User:
<?php
/**
* #ORM\Entity
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
/**
* #ORM\Column(type="string", length=191, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Parking", mappedBy="agents")
*/
private $parkings;
public function __construct()
{
$this->parkings = new ArrayCollection();
}
/**
* #return Collection|Parking[]
*/
public function getParkings(): Collection
{
return $this->parkings;
}
public function addParking(Parking $parking): self
{
if (!$this->parkings->contains($parking)) {
$this->parkings[] = $parking;
$parking->addAgent($this);
return $this;
}
return $this;
}
public function removeParking(Parking $parking): self
{
if ($this->parkings->contains($parking)) {
$this->parkings->removeElement($parking);
$parking->removeAgent($this);
}
return $this;
}
}
Entity Parking:
<?php
/**
* #ORM\Entity(repositoryClass="App\Repository\ParkingRepository")
*/
class Parking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\user", inversedBy="parkings")
*/
private $agents;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
*/
private $voitures;
public function __construct()
{
$this->agents = new ArrayCollection();
$this->voitures = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* #return Collection|user[]
*/
public function getAgents(): Collection
{
return $this->agents;
}
public function addAgent(user $agent): self
{
if (!$this->agents->contains($agent)) {
$this->agents[] = $agent;
}
return $this;
}
public function removeAgent(user $agent): self
{
if ($this->agents->contains($agent)) {
$this->agents->removeElement($agent);
}
return $this;
}
/**
* #return Collection|Voiture[]
*/
public function getVoitures(): Collection
{
return $this->voitures;
}
public function addVoiture(Voiture $voiture): self
{
if (!$this->voitures->contains($voiture)) {
$this->voitures[] = $voiture;
$voiture->setParking($this);
}
return $this;
}
public function removeVoiture(Voiture $voiture): self
{
if ($this->voitures->contains($voiture)) {
$this->voitures->removeElement($voiture);
// set the owning side to null (unless already changed)
if ($voiture->getParking() === $this) {
$voiture->setParking(null);
}
}
return $this;
}
}
And Entity Voiture
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\VoitureRepository")
*/
class Voiture
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $matricule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
/**
* #ORM\Column(type="boolean")
*/
private $parked;
public function getId(): ?int
{
return $this->id;
}
public function getMatricule(): ?string
{
return $this->matricule;
}
public function setMatricule(string $matricule): self
{
$this->matricule = $matricule;
return $this;
}
public function getParking(): ?Parking
{
return $this->parking;
}
public function setParking(?Parking $parking): self
{
$this->parking = $parking;
return $this;
}
}
I propose to add an intermediate entity UserParking between User and Parking entities.
So we have a OneToMany relationship between User and UserParking and a OneToMany relationship between Parking and UserParking instead of ManyToMany relationship between User and Parking.
The entities will be similar to code below:
Entity User:
<?php
/**
* #ORM\Entity
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
/**
* #ORM\Column(type="string", length=191, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="agent")
* #ORM\JoinColumn(nullable=true)
*/
private $user_parking;
// getter and setter
}
Entity Parking:
<?php
/**
* #ORM\Entity(repositoryClass="App\Repository\ParkingRepository")
*/
class Parking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserParking", mappedBy="parking")
* #ORM\JoinColumn(nullable=true)
*/
private $user_parking;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Voiture", mappedBy="parking", orphanRemoval=true)
*/
private $voitures;
// getters and setters
}
Entity UserParking
/**
* UserParking
*
* #ORM\Table(name="user_parking")
* #ORM\Entity(repositoryClass="App\Repository\UserParkingRepository")
*/
class UserParking
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="user_parking")
* #ORM\JoinColumn(nullable=false)
*/
private $agent;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="user_parking")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
// getter and setter
}
And Entity Voiture
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\VoitureRepository")
*/
class Voiture
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $matricule;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Parking", inversedBy="voitures")
* #ORM\JoinColumn(nullable=false)
*/
private $parking;
/**
* #ORM\Column(type="boolean")
*/
private $parked;
}
So to get the cars (voitures) that belong to all parkings the current user is related to you need to:
1- Get the current user object.
2- Get the UserParking array from the user object .
3- Get the Parking objects from the UserParking array.
4- Get the cars from the Parking objects.
The code will be similar to this:
$em = $this->getDoctrine()->getManager();
/* Get user from the session */
$user = $this->getUser();
$userParkings = $user->getUserParking();
$parkings = [];
foreach ($userParkings as $item) {
$parking = $item->getParking();
$parkings[count($parkings)] = $parking;
}
// you can get voitures from parkings
Start from Voiture entity and inner join the Parking and User entities using their associations:
$queryBuilder = $this->getDoctrine()->getRepository('App:Voiture')->createQueryBuilder('v');
$queryBuilder->innerJoin('v.parking', 'p');
$queryBuilder->innerJoin('v.agents', 'a');
Finally, you can filter on the relation either through a condition:
$queryBuilder->where('a.id = :userId');
$queryBuilder->setParameter("userId", 1);
$cars = $queryBuilder->getQuery()->getResult();
or place the condition on the $queryBuilder->innerJoin('v.agents', 'a', 'WITH', 'a.id = :userId'); see doctrine inner join with condition
References
SQL join: where clause vs. on clause

Symfony 3.4 - Extends bundle Entity

I'm working with symfony 3.4 and the bundle l3-db-userbundle, i have a problem when I tried add atributtes to the Entity of bundle...
This is my Entity in AppBundle\Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use L3\Bundle\DbUserBundle\Entity\User;
/**
* XUser
*
* #ORM\Table(name="x_user")
* #ORM\Entity
*/
class XUser extends User
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=100, nullable=false)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="apellido", type="string", length=100, nullable=false)
*/
private $apellido;
/**
* #var string
*
* #ORM\Column(name="dni", type="string", length=20, nullable=false)
*/
private $dni;
/**
* #var string
*
* #ORM\Column(name="uid", type="string", length=15, nullable=false)
*/
private $uid;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="XRole", inversedBy="user")
* #ORM\JoinTable(name="x_user_role",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $role;
/**
* Constructor
*/
public function __construct()
{
$this->role = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* #param string $id
* #return User
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* #param string $nombre
*/
public function setNombre(string $nombre)
{
$this->nombre = $nombre;
}
/**
* #return string
*/
public function getApellido()
{
return $this->apellido;
}
/**
* #param string $apellido
*/
public function setApellido(string $apellido)
{
$this->apellido = $apellido;
}
/**
* #return string
*/
public function getDni()
{
return $this->dni;
}
/**
* #param string $dni
*/
public function setDni(string $dni)
{
$this->dni = $dni;
}
/**
* #return string
*/
public function getUid()
{
return $this->uid;
}
/**
* Set uid
*
* #param string $uid
* #return User
*/
public function setUid($uid) {
$this->uid = $uid;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getRole()
{
return $this->role;
}
/**
* #param \Doctrine\Common\Collections\Collection $role
*/
public function setRole(\Doctrine\Common\Collections\Collection $role)
{
$this->role = $role;
}
}
And this is the class of vendor
<?php
namespace L3\Bundle\DbUserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="x_user")
* #ORM\Entity(repositoryClass="L3\Bundle\DbUserBundle\Repository \UserRepository")
*/
class User implements UserInterface, \Serializable {
/**
* #var integer $id
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="uid", type="string", length=15)
*/
private $uid;
/**
* #ORM\ManyToMany(targetEntity="Role", cascade={"persist"})
* #ORM\JoinTable(name="x_user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
* #var ArrayCollection $roles
*/
private $roles;
public function __construct() {
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set id
*
* #param string $id
* #return User
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* Get uid
*
* #return string
*/
public function getUid() {
return $this->uid;
}
/**
* Set uid
*
* #param string $uid
* #return User
*/
public function setUid($uid) {
$this->uid = $uid;
return $this;
}
//Source : http://www.metod.si/symfony2-error-usernamepasswordtokenserialize-must-return-a-string-or-null/
public function serialize() {
return serialize(array(
$this->id,
$this->uid
));
}
public function unserialize($serialize) {
list(
$this->id,
$this->uid
) = unserialize($serialize);
}
public function eraseCredentials() {
//pas d'implémentation nécessaire
}
public function getPassword() {
//pas d'implémentation nécessaire
}
public function getRoles() {
$roles = array();
foreach ($this->roles as $role) {
if (!in_array($role->getRole(), $roles)) {
$roles[] = $role->getRole();
}
}
$roles[] = "ROLE_USER";
return $roles;
}
public function getSalt() {
//pas d'implémentation nécessaire
}
public function getUsername() {
return $this->getUid();
}
public function __toString() {
return $this->getUid();
}
}
When I try to get data from database, it show me an error: Attempted to call an undefined method named "getNombre" of class "L3\Bundle\DbUserBundle\Entity\User".
This is the method where i have the problem:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\XUser;
use AppBundle\Entity\XUserOffice;
use AppBundle\Form\UserType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class UserController
* #Route("/users")
*/
class UserController extends Controller
{
/**
* #Route("/", name="users_list")
* #Template("#App/user/index.html.twig")
*/
public function indexAction(Request $request)
{
$users = $this->getDoctrine()->getRepository('AppBundle:XUser')->findAll();
$list = [];
foreach ($users as $user) {
$role = $this->getRole($user->getId());
$dat['id'] = $user->getId();
$dat['name'] = $user->getNombre() . ' ' . $user->getApellido();
$dat['dni'] = $user->getDni();
$dat['role'] = $role['role'];
$list[] = $dat;
}
return [
'list' => $list
];
}

Authentication Symfony is not working

I am having a problem with symfony Authentication, the point is, when i create a user, i send a email notification with a token, then when the user click on the link is when his account is activate and i do some verification like the token is correct, the user exist the account is active etc, and after that is when i am having my problem, everything is correctly until the user click on his link i do every verification but when i logged the user automatically and redirect the user to homepage the browser say that is redirecting a lot return $this->redirect($this->generateUrl('homepage'));
well there is when i am having a problem, here is my code on the securityController in activateUserAction is when i am having the problem, i hope someone can helpme
User entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User implements AdvancedUserInterface,\Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* checkMX = true
* )
*
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #Assert\NotBlank(groups={"register"})
* #Assert\Length(min = 6)
*/
private $passwordClear;
/**
* #var bool
*
* #ORM\Column(name="active", type="boolean")
*/
private $active;
/**
* #ORM\Column(type="json_array")
*/
private $roles = array();
/**
* #ORM\Column(name="expired", type="boolean")
*/
private $expired;
/**
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Person",cascade={"persist"})
*/
private $person;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* get PasswordClear
*/
public function getPasswordClear(){
return $this->passwordClear;
}
/**
* set passwordClear
*/
public function setPasswordClear($password){
$this->passwordClear=$password;
}
/**
* Set active
*
* #param boolean $active
*
* #return User
*/
public function setActive($active=0)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return bool
*/
public function getActive()
{
return $this->active;
}
/**
* Set roles
*
* #param array $roles
*
* #return User
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return array($this->roles);
}
/**
* Set person
*
* #param \AppBundle\Entity\Person $person
*
* #return User
*/
public function setPerson(\AppBundle\Entity\Person $person = null)
{
$this->person = $person;
return $this;
}
/**
* Get person
*
* #return \AppBundle\Entity\Person
*/
public function getPerson()
{
return $this->person;
}
public function getUsername()
{
return $this->getEmail();
}
public function eraseCredentials()
{
$this->passwordClear = null;
}
public function getSalt()
{
return null;
}
public function isAccountNonExpired(){
return true;
}
public function isAccountNonLocked(){
return true;
}
public function isCredentialsNonExpired(){
return true;
}
public function isEnabled(){
return $this->active;
}
/**
* Set expired
*
* #param boolean $expired
*
* #return User
*/
public function setExpired($expired)
{
$this->expired = $expired;
return $this;
}
/**
* Get expired
*
* #return boolean
*/
public function getExpired()
{
return $this->expired;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->email,
$this->password,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->email,
$this->password,
) = unserialize($serialized);
}
}
Entity Person
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Kernel;
/**
* Person
*
* #ORM\Table(name="person")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PersonRepository")
*/
class Person
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=255)
*/
private $lastName;
/**
* #var string
* #ORM\Column(name="desccription",type="string", length=255,nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="token", type="string", length=255)
*/
private $token;
/**
* #var string
*
* #ORM\Column(name="url_validate", type="string", length=255)
*/
private $urlValidate;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set lastName
*
* #param string $lastName
*
* #return Person
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set token
*
* #param string $token
*
* #return Person
*/
public function setToken($token)
{
$this->token = $token;
return $this;
}
/**
* Get token
*
* #return string
*/
public function getToken()
{
return $this->token;
}
/**
* Set urlValidate
*
* #param string $urlValidate
*
* #return Person
*/
public function setUrlValidate($urlValidate)
{
$this->urlValidate = $urlValidate;
return $this;
}
/**
* Get urlValidate
*
* #return string
*/
public function getUrlValidate()
{
return $this->urlValidate;
}
}
My securityController
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security
\Core\Authentication\Token \UsernamePasswordToken;
use Symfony\Component\Security
\Http\Firewall\ListenerInterface;
use Symfony\Component\Security
\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security
\Core\Authentication\Token\Storage\TokenStorageInterface;
use AppBundle\Form\RegisterType;
use AppBundle\Entity\Register;
class SecurityController extends Controller
{
/**
* #Route("/login", name="user_login")
*/
public function loginAction()
{
if($this->getUser()){
return $this->redirectToRoute('homepage');
}
$authUtils = $this->get('security.authentication_utils');
return $this->render('front/homepage/_singin.html.twig', array(
'last_username' => $authUtils->getLastUsername(),
'error' => $authUtils->getLastAuthenticationError(),
));
}
/**
* #Route("/login_check", name="user_login_check")
*/
public function loginCheckAction()
{
}
/**
* #Route("/logout", name="user_logout")
*/
public function logoutAction()
{
}
/**
*
* #Route("/token/{token}", name="activate")
*/
public function activateUserAction($token){
$em = $this->getDoctrine()->getManager();
$person=$em->getRepository('AppBundle:Person')->findByToken($token);
if($person){
$user=$em->getRepository('AppBundle:User')->findByPerson($person);
$user->setActive(1);
$person->setToken("");
$person->setActivatedDate(new \DateTime());
$em->persist($person);
$em->flush();
$em->persist($user);
$em->flush();
$token= new UsernamePasswordToken(
$user,
$user->getPassword(),
'user',
$user->getRoles()
);
$this->get('security.token_storage')->setToken($token);
return $this->redirect($this->generateUrl('homepage'));
}else{
return $this->redirect($this->generateUrl('caducada'));
}
}

treeLeft, treeRight and treeLevel value not updated in Symfony 2 Tree

My symfony 2 project require to assign users to a company hierachy. So I try to use tree of StofDoctrineExtension bundle for this project. Here is my Entity class for "category":
<?php
namespace Application\Sonata\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* #Gedmo\Tree(type="nested")
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
*/
class Category
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Column(length=64)
*/
private $title;
/**
* #var integer
*
* #Gedmo\TreeLeft
* #ORM\Column(type="integer")
*/
private $treeLeft;
/**
* #var integer
*
* #Gedmo\TreeLevel
* #ORM\Column(type="integer")
*/
private $treeLevel;
/**
* #var integer
*
* #Gedmo\TreeRight
* #ORM\Column(type="integer")
*/
private $treeRight;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #Gedmo\TreeRoot
* #ORM\Column(type="integer", nullable=true)
*/
private $root;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $children;
/**
* #ORM\OneToMany(targetEntity="User", mappedBy="category")
*/
private $users;
public function __toString()
{
return ($this->title) ? $this->title : '单位';
}
/**
* Constructor
*/
public function __construct()
{
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Category
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get treeLeft
*
* #return integer
*/
public function getTreeLeft()
{
return $this->treeLeft;
}
/**
* Get treeLevel
*
* #return integer
*/
public function getTreeLevel()
{
return $this->treeLevel;
}
/**
* Get treeRight
*
* #return integer
*/
public function getTreeRight()
{
return $this->treeRight;
}
/**
* Get root
*
* #return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Set parent
*
* #param \Application\Sonata\UserBundle\Entity\Category $parent
*
* #return Category
*/
public function setParent(\Application\Sonata\UserBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \Application\Sonata\UserBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Add user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
*
* #return Category
*/
public function addUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
*/
public function removeUser(\Application\Sonata\UserBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
and my CategoryAdmin.php:
......
/**
* {#inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('parent', 'entity', array(
'class' => 'Application\Sonata\UserBundle\Entity\Category', // tree class
'query_builder' => function($er) {
return $er->createQueryBuilder('c')
->orderBy('c.treeLeft', 'ASC');
},
'required' => false,
))
;
}
When I created an category entity, only parent and root value are correctly set, treeLeft, treeRight and treeLevel are zero. I check the sample in the document, it did mention someting about eventlistener. Should I add an eventlestener for this? and How? Thanks for any help.
After I deleted all records and create new one, it works.

Symfony: User roles with doctrine: no entities or tables created

I followed the instructions given in the Symfony-Book to get a user-role relation with doctrine updating them in my database.
Symfony - User/Role - Doctrine
But when I update my entities via doctrine:generate:entities, it only generates the existing User.php, but doesn't touch the Role.php. This wouldn't bother me, if the tables in my databse would update with doctrine:schema:update --force. But they don't. The mentioned tables aren't created. In fact, nothing happens. Can you please help me? I am looking forward to any good solution.
My User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=24, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="isActive", type="string", length=255, nullable=false)
*/
private $isactive;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=10, nullable=false)
*/
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
private $roles;
public function __construct()
{
$this->isActive = true;
$this->roles = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return $this->roles->toArray();
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isactive
*
* #param string $isactive
* #return User
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return string
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* #var string
*/
private $type;
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
}
Role.php:
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="user_role")
* #ORM\Entity()
*/
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;
}
}
First tip: give your user table a different name, eg #ORM\Table(name="acme_user").
Second: add in your user class:
/**
* User's roles.
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
and in your role class
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
#see: http://symfony.com/doc/2.3/cookbook/security/entity_provider.html

Resources