update schema: doesn't work on a child entity - symfony

This is an entity that inherits a BaseUser:
namespace Dolphine\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255)
*/
protected $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255)
*/
protected $lastname;
/**
* #var string
*
* #ORM\Column(name="facebookId", type="string", length=255)
*/
protected $facebookId;
public function serialize()
{
return serialize(array($this->facebookId, parent::serialize()));
}
public function unserialize($data)
{
list($this->facebookId, $parentData) = unserialize($data);
parent::unserialize($parentData);
}
/**
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* #param string $firstname
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
/**
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* #param string $lastname
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
/**
* Get the full name of the user (first + last name)
* #return string
*/
public function getFullName()
{
return $this->getFirstname() . ' ' . $this->getLastname();
}
/**
* #param string $facebookId
* #return void
*/
public function setFacebookId($facebookId)
{
$this->facebookId = $facebookId;
$this->setUsername($facebookId);
}
/**
* #return string
*/
public function getFacebookId()
{
return $this->facebookId;
}
/**
* #param Array
*/
public function setFBData($fbdata)
{
if (isset($fbdata['id'])) {
$this->setFacebookId($fbdata['id']);
$this->addRole('ROLE_FACEBOOK');
}
if (isset($fbdata['first_name'])) {
$this->setFirstname($fbdata['first_name']);
}
if (isset($fbdata['last_name'])) {
$this->setLastname($fbdata['last_name']);
}
if (isset($fbdata['email'])) {
$this->setEmail($fbdata['email']);
}
}
}
After running schema:update --force I get "no changes available for entities", yet my DB table "fos_user" doesn't contain the given fields above.

It appears I had configuration of the bundle set to yml instead of annotations.

Related

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'));
}
}

Doctrine One To Many add column check

I have two Entities
User
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="first_name", type="text", nullable=true)
*/
protected $firstName;
/**
* #ORM\Column(name="last_name", type="text", nullable=true)
*/
protected $lastName;
/**
* #ORM\Column(type="bigint", nullable=true)
*/
protected $phone;
/**
* #ORM\Column(name="birth_date", type="date", nullable=true)
*/
protected $birthDate;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $gender;
/**
* #ORM\Column(name="location_country", type="text", nullable=true)
*/
protected $locationCountry;
/**
* #ORM\Column(name="location_city", type="text", nullable=true)
*/
protected $locationCity;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $avatar;
/**
* #ORM\Column(name="wall_image", type="text", nullable=true)
*/
protected $wallImage;
/**
* #ORM\Column( type="text", nullable=true)
*/
protected $about;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="user")
*/
protected $followers;
/**
* #ORM\OneToMany(targetEntity="Follower", mappedBy="follower")
*/
protected $followings;
/**
* Is followed. Used when checking is followed by another user.
*/
protected $isFollowed = false;
/**
* #ORM\OneToMany(targetEntity="Photo", mappedBy="user")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $photos;
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getPhone()
{
return $this->phone;
}
public function getBirthDate()
{
return $this->birthDate;
}
public function getGender()
{
return $this->gender;
}
public function getLocationCountry()
{
return $this->locationCountry;
}
public function getLocationCity()
{
return $this->locationCity;
}
public function getAvatar()
{
return $this->avatar;
}
public function getAvatarImage()
{
return $this->getAvatarPath().$this->avatar;
}
public function getWallImage()
{
return $this->wallImage;
}
public function getAbout()
{
return $this->about;
}
public function getAvatarPath()
{
return '/web/uploads/avatars/'.$this->id.'/';
}
public function getWallImagePath()
{
return '/web/uploads/wall/'.$this->id.'/';
}
public function getFollowers()
{
return $this->followers;
}
public function getFollowings()
{
return $this->followings;
}
public function getFollowersCount()
{
//print_r($this->followers->toArray());
}
public function getPhotos()
{
return $this->photos;
}
public function isFollowed()
{
return $this->isFollowed;
}
public function setFirstName($value)
{
$this->firstName = $value;
}
public function setLastName($value)
{
$this->lastName = $value;
}
public function setPhone($value)
{
$this->phone = $value;
}
public function setBirthDate($value)
{
$this->birthDate = $value;
}
public function setGender($value)
{
$this->gender = $value;
}
public function setLocationCountry($value)
{
$this->locationCountry = $value;
}
public function setLocationCity($value)
{
$this->locationCity = $value;
}
public function setAvatar($path)
{
$this->avatar = $path;
}
public function setWallImage($path)
{
$this->wallImage = $path;
}
public function setAbout($about)
{
$this->about = $about;
}
public function setFollowed($isFollowed)
{
$this->isFollowed = $isFollowed;
}
}
Photo
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="photos")
*/
class Photo
{
const
CATEGORY_PHOTOGRAPHY = 1,
CATEGORY_PAINTING = 2,
CATEGORY_3D = 3;
/*
* Flow photos limit
*/
const FLOW_PHOTOS_LIMIT = 15;
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="photos")
*/
protected $user;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $title;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* #ORM\Column(type="text")
*/
protected $name;
/**
* #ORM\ManyToOne(targetEntity="PhotoCategory")
*/
protected $category;
/**
* #ORM\Column(name="creation_date", type="datetime")
*/
protected $creationDate;
/**
* #ORM\Column(name="edit_date", type="datetime", nullable=true)
*/
protected $editDate;
/**
* #ORM\Column(name="is_moderated", type="boolean")
*/
protected $isModerated = false;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
protected $isActive = true;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="photo")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $comments;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param User $user
*
* #return Photo
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User $user
*/
public function getUser()
{
return $this->user;
}
/**
* Get category
*
* #return Category $category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set title
*
* #param string $title
*
* #return Photo
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Get editDate
*
* #return \DateTime
*/
public function getEditDate()
{
return $this->editDate;
}
/**
* Get is active
*
* #return integer
*/
public function isActive()
{
return $this->isActive;
}
/**
* Get is moderated
*
* #return integer
*/
public function isModerated()
{
return $this->isModerated;
}
/*
* Get image
*
* #return string
*/
public function getImage()
{
return $this->getWebDirectory().$this->getName();
}
/*
* Get image directory
*
* #return string
*/
public function getDirectory()
{
return __DIR__.'/../../../web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get image web directory
*
* #return string
*/
public function getWebDirectory()
{
return '/web/uploads/photos/'.$this->getUser()->getId().'/'.$this->creationDate->format('Y-m-d').'/';
}
/*
* Get comments
*/
public function getComments()
{
return $this->comments;
}
/**
* Set description
*
* #param string $description
*
* #return Photo
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set name
*
* #param string $name
*
* #return Photo
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
*/
public function setCreationDate(\DateTime $creationDate)
{
$this->creationDate = $creationDate;
}
/**
* Set editDate
*
* #param \DateTime $editDate
*/
public function setEditDate(\DateTime $editDate)
{
$this->editDate = $editDate;
}
/**
* Set active
*/
public function setActive($active)
{
$this->isActive = $active;
}
/**
* Set category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* Set moderated
*/
public function setModerated($moderated)
{
$this->isModerated = $moderated;
}
}
As you see, i have isActive in Photo, which is telling is photo deleted or not. So, i get all users photos via User->getPhotos() which is one-to-many. But it return all users photos. How should be done, so it returns all photos which have isActive = true?
thank you
you can try the filter method to query inside entities
$user->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
There are a number of ways you can do this.
Cosmin provided one for you, which will result in Doctrine loading each photo, and then PHP code checking to see whether or not it is active. This will work in the most number of situations, but will potentially be slow inefficient.
Yet another solution, is to use "criteria":
$exp = new \Doctrine\ORM\Query\Expr();
$activePhotos = $user->getPhotos()->matching(
new \Doctrine\Common\Collections\Criteria(
$exp->eq('active', true)
)
);
This will do something similar to the filter that Cosmin suggested, but allow for Doctrine to filter at the database level.
You can create a method inside the User entity, using the code of #Cosmin Ordean :) Something like this
public function getActivePhotos() {
return $this->getPhotos()->filter(
function($photo) {
return $photo->isActive();
}
);
}

Missing an assigned ID for field

I'm lost in a complexe relation (for me). I've a entity project for an entity client and you can attach users to a project. When i try to add a project without users, no problem. But, when i try to add a project and users Sf2 display this error :
Entity of type Intranet\IntranetBundle\Entity\ProjectUser is missing an assigned ID for field 'project'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
I'm understand it's angry because the project_id is null. But i don't know why it's null.
My Project.php
namespace Intranet\IntranetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Project
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Intranet\IntranetBundle\Entity\ProjectRepository")
*/
class Project
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank(
* message = "The field cannot be empty"
* )
*/
private $name;
/**
* #Gedmo\Slug(fields={"name"})
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="contact_client", type="text", nullable=true)
*/
private $contactClient;
/**
* #var string
*
* #ORM\Column(name="technologies", type="string", length=255, nullable=true)
*/
private $technologies;
/**
* #var string
*
* #ORM\Column(name="languages", type="string", length=255, nullable=true)
*/
private $languages;
/**
* #var string
*
* #ORM\Column(name="extern", type="text", nullable=true)
*/
private $extern;
/**
* #var string
*
* #ORM\Column(name="url_prod", type="string", length=255, nullable=true)
*/
private $urlProd;
/**
* #var string
*
* #ORM\Column(name="url_staging", type="text", nullable=true)
*/
private $urlStaging;
/**
* #var string
*
* #ORM\Column(name="url_dev", type="text", nullable=true)
*/
private $urlDev;
/**
* #var string
*
* #ORM\Column(name="hosting_company", type="string", length=255, nullable=true)
*/
private $hostingCompany;
/**
* #var string
*
* #ORM\Column(name="hosting_type", type="string", length=255, nullable=true)
*/
private $hostingType;
/**
* #var string
*
* #ORM\Column(name="hosting_manager", type="text", nullable=true)
*/
private $hostingManager;
/**
* #var string
*
* #ORM\Column(name="ssh", type="text", nullable=true)
*/
private $ssh;
/**
* #var string
*
* #ORM\Column(name="ftp", type="text", nullable=true)
*/
private $ftp;
/**
* #var string
*
* #ORM\Column(name="db", type="text", nullable=true)
*/
private $db;
/**
* #var string
*
* #ORM\Column(name="emails", type="text", nullable=true)
*/
private $emails;
/**
* #var string
*
* #ORM\Column(name="cms", type="text", nullable=true)
*/
private $cms;
/**
* #var string
*
* #ORM\Column(name="web_services", type="text", nullable=true)
*/
private $webServices;
/**
* #var string
*
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Client", inversedBy="projects")
* #ORM\JoinColumn(nullable=false)
*/
private $client;
/**
* #ORM\OneToMany(targetEntity="Intranet\IntranetBundle\Entity\ProjectUser", mappedBy="project", cascade={"persist"})
*/
private $projectUsers;
public function __construct()
{
$this->projectUsers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Project
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
* #return Client
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set contactClient
*
* #param string $contactClient
* #return Project
*/
public function setContactClient($contactClient)
{
$this->contactClient = $contactClient;
return $this;
}
/**
* Get contactClient
*
* #return string
*/
public function getContactClient()
{
return $this->contactClient;
}
/**
* Set technologies
*
* #param string $technologies
* #return Project
*/
public function setTechnologies($technologies)
{
$this->technologies = $technologies;
return $this;
}
/**
* Get technologies
*
* #return string
*/
public function getTechnologies()
{
return $this->technologies;
}
/**
* Set languages
*
* #param string $languages
* #return Project
*/
public function setLanguages($languages)
{
$this->languages = $languages;
return $this;
}
/**
* Get languages
*
* #return string
*/
public function getLanguages()
{
return $this->languages;
}
/**
* Set extern
*
* #param string $extern
* #return Project
*/
public function setExtern($extern)
{
$this->extern = $extern;
return $this;
}
/**
* Get extern
*
* #return string
*/
public function getExtern()
{
return $this->extern;
}
/**
* Set urlProd
*
* #param string $urlProd
* #return Project
*/
public function setUrlProd($urlProd)
{
$this->urlProd = $urlProd;
return $this;
}
/**
* Get urlProd
*
* #return string
*/
public function getUrlProd()
{
return $this->urlProd;
}
/**
* Set urlStaging
*
* #param string $urlStaging
* #return Project
*/
public function setUrlStaging($urlStaging)
{
$this->urlStaging = $urlStaging;
return $this;
}
/**
* Get urlStaging
*
* #return string
*/
public function getUrlStaging()
{
return $this->urlStaging;
}
/**
* Set urlDev
*
* #param string $urlDev
* #return Project
*/
public function setUrlDev($urlDev)
{
$this->urlDev = $urlDev;
return $this;
}
/**
* Get urlDev
*
* #return string
*/
public function getUrlDev()
{
return $this->urlDev;
}
/**
* Set hostingCompany
*
* #param string $hostingCompany
* #return Project
*/
public function setHostingCompany($hostingCompany)
{
$this->hostingCompany = $hostingCompany;
return $this;
}
/**
* Get hostingCompany
*
* #return string
*/
public function getHostingCompany()
{
return $this->hostingCompany;
}
/**
* Set hostingType
*
* #param string $hostingType
* #return Project
*/
public function setHostingType($hostingType)
{
$this->hostingType = $hostingType;
return $this;
}
/**
* Get hostingType
*
* #return string
*/
public function getHostingType()
{
return $this->hostingType;
}
/**
* Set hostingManager
*
* #param string $hostingManager
* #return Project
*/
public function setHostingManager($hostingManager)
{
$this->hostingManager = $hostingManager;
return $this;
}
/**
* Get hostingManager
*
* #return string
*/
public function getHostingManager()
{
return $this->hostingManager;
}
/**
* Set ssh
*
* #param string $ssh
* #return Project
*/
public function setSsh($ssh)
{
$this->ssh = $ssh;
return $this;
}
/**
* Get ssh
*
* #return string
*/
public function getSsh()
{
return $this->ssh;
}
/**
* Set ftp
*
* #param string $ftp
* #return Project
*/
public function setFtp($ftp)
{
$this->ftp = $ftp;
return $this;
}
/**
* Get ftp
*
* #return string
*/
public function getFtp()
{
return $this->ftp;
}
/**
* Set db
*
* #param string $db
* #return Project
*/
public function setDb($db)
{
$this->db = $db;
return $this;
}
/**
* Get db
*
* #return string
*/
public function getDb()
{
return $this->db;
}
/**
* Set emails
*
* #param string $emails
* #return Project
*/
public function setEmails($emails)
{
$this->emails = $emails;
return $this;
}
/**
* Get emails
*
* #return string
*/
public function getEmails()
{
return $this->emails;
}
/**
* Set cms
*
* #param string $cms
* #return Project
*/
public function setCms($cms)
{
$this->cms = $cms;
return $this;
}
/**
* Get cms
*
* #return string
*/
public function getCms()
{
return $this->cms;
}
/**
* Set webServices
*
* #param string $webServices
* #return Project
*/
public function setWebServices($webServices)
{
$this->webServices = $webServices;
return $this;
}
/**
* Get webServices
*
* #return string
*/
public function getWebServices()
{
return $this->webServices;
}
/**
* Set comment
*
* #param string $comment
* #return Project
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set client
*
* #param \Intranet\IntranetBundle\Entity\Client $client
* #return Project
*/
public function setClient(\Intranet\IntranetBundle\Entity\Client $client)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* #return \Intranet\IntranetBundle\Entity\Client
*/
public function getClient()
{
return $this->client;
}
public function addProjectUser(\Intranet\IntranetBundle\Entity\ProjectUser $projectUser)
{
$this->projectUsers[] = $projectUser;
}
public function removeProjectUser(\Intranet\IntranetBundle\Entity\ProjectUser $projectUser)
{
$this->projectUsers->removeElement($projectUser);
}
public function getProjectUsers()
{
return $this->projectUsers;
}
}
My ProjectUser.php
namespace Intranet\IntranetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class ProjectUser
{
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Project", inversedBy="projectUsers")
*/
private $project;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Intranet\UserBundle\Entity\User")
*/
private $user;
/**
* #ORM\Column(name="profil", type="smallint")
*/
private $profil;
public function setProject(\Intranet\IntranetBundle\Entity\Project $project)
{
$project->addProjectUser($this);
$this->project = $project;
}
public function getProject()
{
return $this->project;
}
public function setUser(\Intranet\UserBundle\Entity\User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function setProfil($profil)
{
$this->profil = $profil;
}
public function getProfil()
{
return $this->profil;
}
}
profil = smallint for the job of the user (1=manager, 2=designer, ...)
My ProjectController (addAction)
public function addAction()
{
$project = new Project;
$form = $this->createForm(new ProjectType, $project);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($project);
$em->flush();
foreach ($form->get('projectUsers')->getData() as $u) {
$u->setProject($project);
$em->persist($u);
}
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'The project : '. $project->getName() .' has been added');
return $this->redirect($this->generateUrl('clients_list'));
}
}
return $this->render('IntranetIntranetBundle:Project:add_project.html.twig', array(
'form' => $form->createView()
));
}
Thanks for your help
Well, first of all, you shouldn't specify #ORM\Id annotation on every foreign key in your ProjectUser entity - it is for primary keys.
Then you should declare column join on foreign key fields:
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Project", inversedBy="projectUsers")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\User", inversedBy="projects")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
You also should have a field like
class User
{
// ...
/**
* #ORM\OneToMany(targetEntity="Intranet\IntranetBundle\Entity\ProjectUser", mappedBy="user")
*/
private $projects;
// ...
}
Finally, to add user to project, I suggest you embed a ProjectUserType form with user selection into ProjectType form. In your controller, you can have something like
public function addAction()
{
$project = new Project;
$projectUser = new ProjectUser();
$projectUser->setProject($project);
$project->addProjectUser($projectUser);
$form = $this->createForm(new ProjectType, $project);
// ...
And in form ProjectUserType
class ProjectUserType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('user', 'entity', array(
'class' => 'Intranet:IntranetBundle:User'
));
// ...
Hope this helps at least a little bit.
When you code : $em->persist($project);
$project is equal to $project = new Project; (don't you have forget '()' ?)
Actually the $projet is empty... To do this, I think you forget to code :
$project = $form->getData();

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