Doctrine. One to many. How to write annotations? - symfony

I have a OneToMany relation between two tables 'user' and 'profil'
(a user has one only profile, and a profile can be asseigned to many users)
I'm getting this error whenever I try to update the schema in doctrine console.
here is my two entities :
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping\ManyToOne;
/**
* user
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class user
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
public function __construct()
{
}
/**
* #var boolean
*
* #ORM\Column(name="etat", type="boolean")
*/
private $etat;
/**
* #var profil $profil
*
* #ORMManyToOne(targetEntity="profil", inversedBy="users", cascade={"persist", "merge"})
* #ORMJoinColumns({
* #ORMJoinColumn(name="profil", referencedColumnName="id")
* })
*/
private $profil;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* #param integer $id
* #return user
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* 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;
}
/**
* Set etat
*
* #param boolean $etat
* #return user
*/
public function setEtat($etat)
{
$this->etat = $etat;
return $this;
}
/**
* Get etat
*
* #return boolean
*/
public function getEtat()
{
return $this->etat;
}
/**
* Get profil
*
* #return integer
*/
public function getProfil()
{
return $this->profil;
}
/**
* Set profil
*
* #param integer $profil
* #return user
*/
public function setProfil($profil)
{
$this->profil = $profil;
return $this;
}
public function getUsername()
{
return $this->id;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return $user->getId() == $this->getId();
}
}
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\OneToMany;
/**
* profil
*
* #ORM\Table(name="profil")
* #ORM\Entity
*/
class profil
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libelle", type="string", length=20)
*/
private $libelle;
/**
* #var ArrayCollection $users
*
* #ORMOneToMany(targetEntity="user", mappedBy="profil", cascade={"persist", "remove", "merge"})
*/
private $users;
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set libelle
*
* #param string $libelle
* #return profil
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set id
*
* #param integer $id
* #return profil
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
public function __toString() {
return $this->libelle;
}
}

You have syntax mistake.
#ORMManyToOne - this is mistake.
#ORM\ManyToOne(targetEntity="Profil", inversedBy="users")
Above will be correct. And everywhere you use ORM You need to write ORM\something. ORM - is just a namespace, or simply path to the ORM classes in doctrine vendor directory!
Every class name should start with capital letter. It is a wright way! So you should write class User, but not class user!
You didn't show in Profil class, that you have a lot of users to each profil. the users field will be of array collection type (simple array but with useful methods.) So in Profil class in __construct() method:
public function __construct()
{
$this->users = new ArrayCollection();
}
You have One-To-Many, Bidirectional relation.
You can say :
Every (ONE) profile can have a lot of (MANY) users, which use it (One-To-Many)
Every user can use only one exact profile
So try this
// Class Profil
/**
* Bidirectional - One-To-Many (INVERSED SIDE)
* One Profile can have many users, which use it
*
* #var ArrayCollection $users
*
* #ORM\OneToMany(targetEntity="Path-to-your-user-class\Users", mappedBy="profil", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
// Class user
/**
* Bidirectional - One-To-Many (OWNER SIDE)
* One user have only one profile (or profil)
*
* #var Profil $profil
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Profil", inversedBy="users")
* #ORM\JoinColumn(name="profil_id", referencedColumnName="id")
*/
private $profil;

Related

Symfony and Doctrine databases

I am working on some new project and the project is nearly done using Symfony framework, but the problem that i am used to CodeIgnitor Framework and basically as a Java developer/Android a lot of stuff i got confused with when working on Web development so here is the situation:
The website have a user end and an admin end (i am working on the Admin end), so there are these tables in the database which i really don't understand why they are built like this but this is not the problem
what i would like to know is how to add a service_category field with the corresponding translations in the service_category_translation using forms or any other way
this is the ServiceCategory Entity
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation as Serializer;
/**
* class ServiceCategory
*
* #ORM\Table(name="service_category")
* #ORM\Entity
*
* #Serializer\ExclusionPolicy("all")
*/
class ServiceCategory
{
use ORMBehaviors\Timestampable\Timestampable;
use ORMBehaviors\SoftDeletable\SoftDeletable;
use ORMBehaviors\Translatable\Translatable;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #Serializer\Expose
* #Serializer\Groups({"general-information", "service-offer"})
*/
private $id;
/**
* #var ServiceGroup
*
* #ORM\OneToMany(targetEntity="ServiceGroup", mappedBy="serviceCategory")
*
* #Serializer\Expose
* #Serializer\Groups({"service-offer"})
*/
private $serviceGroup;
/**
* Constructor
*/
public function __construct()
{
$this->serviceGroup = new ArrayCollection();
}
/**
* {#inheritdoc}
*/
public function __toString()
{
return $this->getName() ? $this->getName() : '';
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Get translated name
*
* #return string
*
* #Serializer\VirtualProperty
* #Serializer\SerializedName("name")
* #Serializer\Groups({"invoice-list", "service-offer"})
*/
public function getName()
{
if($this->getTranslations()->get($this->getCurrentLocale()) == null){
return 'sorry';
}
return $this->getTranslations()->get($this->getCurrentLocale())->getName();
}
/**
* Add serviceGroup
*
* #param ServiceGroup $serviceGroup
*
* #return ServiceCategory
*/
public function addServiceGroup(ServiceGroup $serviceGroup)
{
$this->serviceGroup[] = $serviceGroup;
return $this;
}
/**
* Remove serviceGroup
*
* #param ServiceGroup $serviceGroup
*/
public function removeServiceGroup(ServiceGroup $serviceGroup)
{
$this->serviceGroup->removeElement($serviceGroup);
}
/**
* Get serviceGroup
*
* #return Collection
*/
public function getServiceGroup()
{
return $this->serviceGroup;
}
}
and this is the ServiceCategoryTranslation Entity
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* Class ServiceCategoryTranslation
*
* #package CoreBundle\Entity
*
* #ORM\Entity
* #ORM\Table(name="service_category_translation")
*/
class ServiceCategoryTranslation
{
use ORMBehaviors\Translatable\Translation;
use ORMBehaviors\Timestampable\Timestampable;
use ORMBehaviors\SoftDeletable\SoftDeletable;
/**
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param string
* #return null
*/
public function setName($name)
{
$this->name = $name;
}
public function __toString() {
return $this->name;
}
}
how can i achieve this ?
please don't guide me to symfony or doctrine documentation i have been lost there for two days now and i am running late on the schedule
Thanks in advance
You have a one-to-many-association from ServiceCategory (1) to ServiceCategoryTranslations (many) since I assume you
will manage the transaltions from the category. This have to be a bidirectional association, have a look
here
You have to add a property to manage the entities and describe the association. I will do it with annotations.
use Doctrine\Common\Collections\ArrayCollection;
class ServiceCategory
{
/**
* #OneToMany(targetEntity="ServiceCategoryTranslation", mappedBy="serviceCategory")
**/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
/**
* #return ServiceCategoryTranslation[]
*/
public function getStandort(){
return $this->translations;
}
/**
* #param ArrayCollection $translations
* #return ServiceCategory
*/
public function setTranslations(ArrayCollection $translations)
{
$this->translations->clear();
foreach ($translations as $translation){
$this->addTranslation($translation);
}
return $this;
}
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategory
*/
public function addTranslation(ServiceCategoryTranslation $translation){
/* this is a way to keep the integerity */
$translation->setServiceCategory($this);
if(!$this->translation){
$this->translations = new ArrayCollection();
}
$this->translations->add($translation);
return $this;
}
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategory
*/
public function removeStandort(ServiceCategoryTranslation $translation){
$this->translations->removeElement($translation);
return $this;
}
}
class ServiceCategoryTranslation
{
/**
* #ManyToOne(targetEntity="ServiceCategory", inversedBy="translations")
* #JoinColumn(name="translatable_id", referencedColumnName="id")
**/
private $serviceCategory;
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategoryTranslation
*/
public function setServiceCategory(ServiceCategory $serviceCategory){
$this->serviceCategory = $serviceCategory;
return $this;
}
/* getter analog */
}

Symfony 2 doctrine DQL order by two fields

Hi guys i have two objects Point and Subpoint when i got from the repository with custom DQL The point i want to order the Points by field ord and the Subpoints to field ord.
Here is the Entities:
namespace George\ArchitectureBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
/**
* Point
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="George\ArchitectureBundle\Entity\PointRepository")
* #Vich\Uploadable
*/
class Point
{
use Translatable;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Object
* #Gedmo\SortableGroup
* #ORM\ManyToOne(targetEntity="George\ObjectsBundle\Entity\Object", inversedBy="architecturespoints")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*/
private $object;
/**
* #ORM\OneToMany(targetEntity="George\ArchitectureBundle\Entity\Subpoint", mappedBy="point")
*/
private $subpoints;
/**
* #var integer
* #Gedmo\SortablePosition
* #ORM\Column(name="ord", type="integer")
*/
private $ord;
/**
* #var \DateTime
* #Gedmo\Timestampable(on="update")
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var \DateTime
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->subpoints = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return Object
*/
public function getObject()
{
return $this->object;
}
/**
* #param Object $object
*/
public function setObject($object)
{
$this->object = $object;
}
/**
* #return int
*/
public function getOrd()
{
return $this->ord;
}
/**
* #param int $ord
*/
public function setOrd($ord)
{
$this->ord = $ord;
}
/**
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* #return mixed
*/
public function getSubpoints()
{
return $this->subpoints;
}
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="point_image", fileNameProperty="imageName")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #var string
*/
private $imageName;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
// $this->setModefied(new \DateTime('now')) ;
}
}
/**
* #return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
}
/**
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
}
Subpoint:
namespace George\ArchitectureBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
/**
* Subpoint
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="George\ArchitectureBundle\Entity\SubpointRepository")
* #Vich\Uploadable
*/
class Subpoint
{
use Translatable;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Points
* #Gedmo\SortableGroup
* #ORM\ManyToOne(targetEntity="George\ArchitectureBundle\Entity\Point", inversedBy="subpoints")
*/
private $point;
/**
* #var integer
* #Gedmo\SortablePosition
* #ORM\Column(name="ord", type="integer")
*/
private $ord;
/**
* #var \DateTime
* #Gedmo\Timestampable(on="update")
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var \DateTime
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return Points
*/
public function getPoint()
{
return $this->point;
}
/**
* #param Points $point
*/
public function setPoint($point)
{
$this->point = $point;
}
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="point_image", fileNameProperty="imageName")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #var string
*/
private $imageName;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
// $this->setModefied(new \DateTime('now')) ;
}
}
/**
* #return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
}
/**
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
/**
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* #return int
*/
public function getOrd()
{
return $this->ord;
}
/**
* #param int $ord
*/
public function setOrd($ord)
{
$this->ord = $ord;
}
}
Repository Point and here i want when i got the Point to be oredered by ord and the subpoints to be ordered by ord:
namespace George\ArchitectureBundle\Entity;
/**
* PointRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PointRepository extends \Doctrine\ORM\EntityRepository
{
public function getPointsByObject($object)
{
$em = $this->getEntityManager();
$query = $em->createQuery("SELECT p FROM George\ArchitectureBundle\Entity\Point p WHERE p.object =".$object." ORDER BY p.ord ASC");
return $query->getResult();
}
}
But when i put in the creatQuery in Point repository
"SELECT p FROM George\ArchitectureBundle\Entity\Point p WHERE p.object =".$object." ORDER BY p.ord ASC, p.subpoints.ord ASC "
I got error:
[Semantical Error] line 0, col 107 near 'ord ASC ': Error: Class George\ArchitectureBundle\Entity\Point has no field or association named subpoints.ord
EDIT
The solution to the problem is this with query builder with guidance of #Yoshi and #Veve:
public function getPointsByObject($object)
{
$em = $this->getEntityManager();
// $query = $em->createQuery("SELECT p FROM George\ArchitectureBundle\Entity\Point p left join George\ArchitectureBundle\Entity\Subpoint s WITH s.point = p WHERE p.object =".$object." ORDER BY p.ord ASC, s.ord ASC");
$qb = $em->createQueryBuilder();
$qb->select('p')
->from('George\ArchitectureBundle\Entity\Point','p')
->where(' p.object =:object')
->leftJoin('George\ArchitectureBundle\Entity\Subpoint', 's', 'WITH', 's.point = p')
->orderBy('p.ord','ASC')
->orderBy('s.ord','ASC');
$qb->setParameters(array(
'object' => $object
));
$query= $qb->getQuery();
return $query->getResult();
}
You have to join the subpoint to order by one of its attributes:
"SELECT p FROM George\ArchitectureBundle\Entity\Point p
JOIN George\ArchitectureBundle\Entity\Subpoint s WITH s.point = p.id
WHERE p.object =".$object."
ORDER BY p.ord ASC, s.ord ASC"
And as Yoshi commented, you should use the queryBuilder and add your parameters with it instead of building your query by hand.

symfony2, doctrine2, class inheritance

I'm playing a little with doctrine and symfony and i encountered a problem with this model.
I setup a base class ( entity ) and then a child class ( entity ), so far everything works smooth after that i wanted to add more fields to my table and i used doctrine:generate:entities BundleName. And here is the problem. If i do not set the variables from base class to protected symfony / doctrine says it cannot access that variable but if i set it as protected and generate the entities again it creates getters and setters for the protected variables from base class in my child class which i find it weird so i googled a little but i only found one topic about this problem and didn't had an answer for it.
The Base Class got set the annotation MappedSuperclass but .. didn't had any effect on it.
Base class which implements AdvancedUserInterface
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
/**
* #ORM\MappedSuperclass
*/
class BaseUser implements AdvancedUserInterface
{
/**
* #var string
* #ORM\Column(name="username", type="string", length=255, nullable=true)
*/
protected $username;
/**
* #var string
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #var bool
* #ORM\Column(name="isActive", type="boolean")
*/
protected $isActive = '0';
/**
* [$isAccountNonExpired description].
*
* #var bool
* #ORM\Column(name="isAccountNonExpired", type="boolean")
*/
protected $isAccountNonExpired = '1';
/**
* [$isAccountNonLocked description].
*
* #var bool
* #ORM\Column(name="isAccountNonLocked", type="boolean")
*/
protected $isAccountNonLocked = '0';
/**
* [$isCredentialsNonExpired description].
*
* #var bool
* #ORM\Column(name="isCredentialsNonExpired", type="boolean")
*/
protected $isCredentialsNonExpired = '0';
/**
* 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;
}
/**
* 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;
}
/**
* USER INTERFACE IMPLEMENTATION.
*/
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
}
public function getRoles()
{
return array('ROLE_ADMIN');
}
public function eraseCredentials()
{
return $this->plainPassword = null;
}
/**
* ADVANCED USER INTERFACE IMPLEMENTATION.
*/
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
return $this->isAccountNonExpired;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
return $this->isAccountNonLocked;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return $this->isCredentialsNonExpired;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
return $this->isActive;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return BaseUser
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set isAccountNonExpired
*
* #param boolean $isAccountNonExpired
* #return BaseUser
*/
public function setIsAccountNonExpired($isAccountNonExpired)
{
$this->isAccountNonExpired = $isAccountNonExpired;
return $this;
}
/**
* Get isAccountNonExpired
*
* #return boolean
*/
public function getIsAccountNonExpired()
{
return $this->isAccountNonExpired;
}
/**
* Set isAccountNonLocked
*
* #param boolean $isAccountNonLocked
* #return BaseUser
*/
public function setIsAccountNonLocked($isAccountNonLocked)
{
$this->isAccountNonLocked = $isAccountNonLocked;
return $this;
}
/**
* Get isAccountNonLocked
*
* #return boolean
*/
public function getIsAccountNonLocked()
{
return $this->isAccountNonLocked;
}
/**
* Set isCredentialsNonExpired
*
* #param boolean $isCredentialsNonExpired
* #return BaseUser
*/
public function setIsCredentialsNonExpired($isCredentialsNonExpired)
{
$this->isCredentialsNonExpired = $isCredentialsNonExpired;
return $this;
}
/**
* Get isCredentialsNonExpired
*
* #return boolean
*/
public function getIsCredentialsNonExpired()
{
return $this->isCredentialsNonExpired;
}
}
And child class
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Gedmo\Mapping\Annotation as Gedmo;
use AppBundle\Entity\BaseUser;
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Zenith\UserBundle\Entity\UserRepository")
* #UniqueEntity(fields="email", message="Email already taken")
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User extends BaseUser
{
/**
* #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)
* #Assert\Email()
* #Assert\NotBlank()
*/
private $email;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(max = 4096)
*/
protected $plainPassword;
/**
* Date when the user needs to change his password
* for security reasons.
*
* #var datetime
*
* #ORM\Column(name="credentialsExpireAt", type="datetime", nullable=true)
*/
private $credentialsExpireAt;
/**
* Date when the account expires
* This can be used for temporary accounts.
*
* #var datetime
*
* #ORM\Column(name="accountExpireAt", type="datetime", nullable=true)
*/
private $accountExpireAt;
/**
* Saves last login date of the user.
*
* #var datetime
* #ORM\Column(name="lastLogin", type="datetime", nullable=true)
*/
private $lastLogin;
/**
*
*
* #ORM\Column(name="createdAt", type="datetime")
* #Gedmo\Timestampable(on="create")
*
* #var datetime
*/
private $createdAt;
/**
* #ORM\Column(name="editedAt", type="datetime")
* #Gedmo\Timestampable(on="update")
*
* #var datetime
*/
private $editedAt;
/**
* Get id
*
* #return integer
*/
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 credentialsExpireAt
*
* #param \DateTime $credentialsExpireAt
* #return User
*/
public function setCredentialsExpireAt($credentialsExpireAt)
{
$this->credentialsExpireAt = $credentialsExpireAt;
return $this;
}
/**
* Get credentialsExpireAt
*
* #return \DateTime
*/
public function getCredentialsExpireAt()
{
return $this->credentialsExpireAt;
}
/**
* Set accountExpireAt
*
* #param \DateTime $accountExpireAt
* #return User
*/
public function setAccountExpireAt($accountExpireAt)
{
$this->accountExpireAt = $accountExpireAt;
return $this;
}
/**
* Get accountExpireAt
*
* #return \DateTime
*/
public function getAccountExpireAt()
{
return $this->accountExpireAt;
}
/**
* Set lastLogin
*
* #param \DateTime $lastLogin
* #return User
*/
public function setLastLogin($lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* Get lastLogin
*
* #return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set editedAt
*
* #param \DateTime $editedAt
* #return User
*/
public function setEditedAt($editedAt)
{
$this->editedAt = $editedAt;
return $this;
}
/**
* Get editedAt
*
* #return \DateTime
*/
public function getEditedAt()
{
return $this->editedAt;
}
}
So what is the question? Why the command do so? Or how to use it in this case?
doctrine:generate:entities generates an entity class from it's mapping. The mapping may be described in different formats, and PHP annotation is only one of them (along with xml and yml). I suppose the logic works that way - first from annotations mapping is creating, and later from mapping (regardless how this mapping was described, and if properties were inherited on no) is generated a class.
So don't worry, remove unnecessary code and move on. This is only a tool that saves some time.

Sonata AdminBundle, get the parameter of an entity

I have an entity Prototype with a relation many to one with project and I want to override a function in the CRUDController.
Here is the code :
$idPrototype = $this->get('request')->get($this->admin->getIdParameter());
I get the id of the prototype, but I want the parameter 'project' ( the id of the project )
Here is my prototype entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Prototype
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\PrototypeRepository")
*/
class Prototype
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreation", type="date")
*/
private $dateCreation;
private $projet;
public function __construct()
{
$this->dateCreation = new \DateTime("now");
$this->nom = "";
$this->description = " ";
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
public function __toString()
{
return $this->getNom();
}
/**
* Set nom
*
* #param string $nom
* #return Prototype
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Set description
*
* #param string $description
* #return Prototype
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Prototype
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set projet
*
* #param \AppBundle\Entity\Projet $projet
* #return Prototype
*/
public function setProjet(\AppBundle\Entity\Projet $projet = null)
{
$this->projet = $projet;
return $this;
}
/**
* Get projet
*
* #return \AppBundle\Entity\Projet
*/
public function getProjet()
{
return $this->projet;
}
}
I've tried to use ModelManager() but I get this error "Attempted to call an undefined method named "getModelManager" of class "AppBundle\Controller\CRUDProtoController". "
I'm new with sonata and symfony and I find difficulties with it.

Symfony2 "Error: Call to a member function toArray() on a non-object" when loading Roles from Database

I've been battling with this for several hours. I've built an app in Symfony 2.5 and when I go to log in as a user I receive this error:
FatalErrorException: Error: Call to a member function toArray() on a
non-object in /var/www/cwwa/src/CWWA/CoreBundle/Entity/Users.php line
402
On line 402, I have this code:
/**
* #inheritDoc
*/
public function getRoles()
{
//return array('ROLE_CUSTOMER_USER');
return $this->roles->toArray();
}
If I comment out return $this->roles->toArray(); and replace it with the line above it, my user gets logged in to the system without an issue.
Now the main issue I see other people having has been with Symfony2 running on a server with PHP 5.4. My laptop was running this until I downgraded it to 5.3. This hasn't solved the issue.
Another method I used was to replace return $this->roles->toArray(); to return $this->roles;, I get this error:
Catchable Fatal Error: Argument 4 passed to
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::__construct()
must be an array, integer given, called in
/var/www/cwwa/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php
on line 96 and defined in
/var/www/cwwa/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php
line 36
I assume from this that the system is retrieving a value from the database.
My Database uses two tables for security. One User table and the other is the Role table. I've included the Entity files for both the User and Role tables below:
Users.php
<?php
namespace CWWA\CoreBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Users
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="CWWA\CoreBundle\Entity\Users")
*/
class Users implements UserInterface, \Serializable
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=500, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=500, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=500, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=500, nullable=false)
*/
private $salt;
/**
* #var string
*
* #ORM\Column(name="first_name", type="string", length=125, nullable=false)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="surname", type="string", length=45, nullable=false)
*/
private $surname;
/**
* #var integer
*
* #ORM\Column(name="customer", type="integer", nullable=false)
*/
private $customer;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime", nullable=false)
*/
private $created;
/**
* #var boolean
*
* #ORM\Column(name="is_active", type="boolean", nullable=false)
*/
private $isActive;
/**
* #var boolean
*
* #ORM\Column(name="blocked", type="boolean", nullable=false)
*/
private $blocked;
/**
* #var integer
*
* #ORM\Column(name="access_list", type="integer", nullable=false)
*/
private $accessList;
/**
* #ORM\ManyToMany(targetEntity="Roles", inversedBy="roles")
*
*/
private $roles;
public function __construct()
{
return $this->isActive = true;
return $this->salt = md5(uniqid(null, true));
return $this->roles = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set email
*
* #param string $email
* #return Users
*/
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 Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set salt
*
* #param string $salt
* #return Users
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set firstName
*
* #param string $firstName
* #return Users
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set surname
*
* #param string $surname
* #return Users
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set customer
*
* #param integer $customer
* #return Users
*/
public function setCustomer($customer)
{
$this->customer = $customer;
return $this;
}
/**
* Get customer
*
* #return integer
*/
public function getCustomer()
{
return $this->customer;
}
/**
* Set created
*
* #param \DateTime $created
* #return Users
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return Users
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set blocked
*
* #param boolean $blocked
* #return Users
*/
public function setBlocked($blocked)
{
$this->blocked = $blocked;
return $this;
}
/**
* Get blocked
*
* #return boolean
*/
public function getBlocked()
{
return $this->blocked;
}
/**
* Set accessList
*
* #param integer $accessList
* #return Users
*/
public function setAccessList($accessList)
{
$this->accessList = $accessList;
return $this;
}
/**
* Get accessList
*
* #return integer
*/
public function getAccessList()
{
return $this->accessList;
}
/**
* Set roles
*
* #param integer $roles
* #return Users
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* #inheritDoc
*/
public function getRoles()
{
//return array('ROLE_CUSTOMER_USER');
return $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 isEqualTo(UserInterface $user)
{
return $this->id === $user->getId();
}
}
Roles.php
<?php
namespace CWWA\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\Role\RoleInterface;
/**
* Roles
*
* #ORM\Table(name="roles")
* #ORM\Entity
*/
class Roles implements RoleInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="names", type="string", length=30, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="role", type="string", length=20, nullable=false)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="Users", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set names
*
* #param string $names
* #return Roles
*/
public function setNames($names)
{
$this->names = $names;
return $this;
}
/**
* Get names
*
* #return string
*/
public function getNames()
{
return $this->names;
}
/**
* 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;
}
}
Any help would be fantastic, especially after 4 hours of hitting brick walls!
In your User entity, the roles field should be inversed by users (the field on the other side of the entity).
/**
* #ORM\ManyToMany(targetEntity="Roles", inversedBy="users")
*/
private $roles;
You might need to update your database.
I had a similar problem. The toArray() method isn't working because $this->roles is not an instance of ArrayCollection, instead it's an integer. I don't quite understand why you have three return statements in your Users constructor function; try getting rid of those first and just set the properties you need to set:
public function __construct()
{
$this->isActive = true;
$this->salt = md5(uniqid(null, true));
$this->roles = new ArrayCollection();
}
Now the toArray() method should work as $this->roles should be an ArrayCollection(). Just remember that the Symfony security layer expects either an array of role objects or an array of strings.

Resources