Invalid Entities Category And Product - symfony

I have 2 entities - Product and category.
But i have in symfony dev toolbar the error - Invalid Entities 2.
The exact error is:
Entities Mapping
Class Mapping errors
AppBundle\Entity\category
The association AppBundle\Entity\category#products refers to the owning side field AppBundle\Entity\Product#category which does not exist.
AppBundle\Entity\Product
The association AppBundle\Entity\Product#categoryId refers to the inverse side field AppBundle\Entity\category#product which does not exist.here
I've tried many times fix the relastion following symfony docs, but it dosn't works.
So, please, tell were am i wrong....
Here are my 2 entities:
Product
<?php
namespace AppBundle\Entity;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* #ORM\Table(name="products")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
*/
class Product
{
/**
* #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="sku", type="string", length=255, unique=true)
*/
private $sku;
/**
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\category", inversedBy="product")
* #ORM\JoinColumn(name="categoryId", referencedColumnName="id")
*/
private $categoryId;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255, nullable=true)
* #Assert\File(
* maxSize="5242880",
* mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* "image/gif",
* }
* )
*/
private $image;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", precision=10, scale=2, nullable=true)
*/
private $price;
/**
* #var bool
*
* #ORM\Column(name="isActive", type="boolean", nullable=true)
*/
private $isActive;
/**
* #var int
*
* #ORM\Column(name="quantity", type="integer", nullable=true)
*/
private $quantity;
/**
* #var decimal
*/
private $percent;
/**
* #var decimal
*/
private $endPrice;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sku
*
* #param string $sku
*
* #return Product
*/
public function setSku($sku)
{
$this->sku = $sku;
return $this;
}
/**
* Get sku
*
* #return string
*/
public function getSku()
{
return $this->sku;
}
/**
* Set categoryId
*
* #param integer $categoryId
*
* #return Product
*/
public function setCategoryId($categoryId)
{
$this->categoryId = $categoryId;
return $this;
}
/**
* Get categoryId
*
* #return int
*/
public function getCategoryId()
{
return $this->categoryId;
}
/**
* Set image
*
* #param string $image
*
* #return Product
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set isActive
*
* #param boolean $isActive
*
* #return Product
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return bool
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return Product
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* #return decimal
*/
public function getPercent()
{
return $this->percent;
}
/**
* #param decimal $percent
*/
public function setPercent($percent)
{
if(null != $percent) {
$this->percent = $percent;
}
}
/**
* #return decimal
*/
public function getEndPrice()
{
return $this->endPrice;
}
/**
* #param decimal $endPrice
*/
public function setEndPrice($endPrice)
{
$this->endPrice = $endPrice;
}
}
.........................................................................................................................................................................................................................................
category
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* category
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="AppBundle\Repository\categoryRepository")
*/
class category
{
/**
* #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 int
*
* #ORM\Column(name="parent", type="integer", nullable=true)
*/
private $parent;
/**
* #var bool
*
* #ORM\Column(name="isActive", type="boolean", nullable=true)
*/
private $isActive;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Product" , mappedBy="category")
*/
private $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set parent
*
* #param integer $parent
*
* #return category
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return int
*/
public function getParent()
{
return $this->parent;
}
/**
* Set isActive
*
* #param boolean $isActive
*
* #return category
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return bool
*/
public function getIsActive()
{
return $this->isActive;
}
public function __toString()
{
return $this->id."";
}
/**
* #return mixed
*/
public function getProducts()
{
return $this->products;
}
/**
* #param mixed $products
*/
public function setProducts($products)
{
$this->products = $products;
}
}
How to fix it?

Try replacing in Product entity this
private $categoryId;
By this
private $category;
Don't forget to change the getter & setter

try to change this:
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\category", inversedBy="product")
to this:
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
and this:
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Product" , mappedBy="category")
to this:
* #ORM\OneToMany(targetEntity="Product" , mappedBy="category")

Related

The mappings and are inconsistent with each other?

Query Warning message from Symfony Profiler:
Klient Entity
The mappings AdminBundle\Entity\Klient#contacts and
AdminBundle\Entity\KlientContact#fkKlient
are inconsistent with each other.
KlientContact Entity
The association AdminBundle\Entity\KlientContact#fkKlient refers to
the inverse side field AdminBundle\Entity\Klient#nip which is not
defined as association. The association
AdminBundle\Entity\KlientContact#fkKlient refers to the inverse side
field AdminBundle\Entity\Klient#nip which does not exist.
What did I do wrong ? I assume that there is something that I am missing on Klient#nip (which is mapped as Id field)
[Klient Entity]
<?php
namespace AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AdminBundle\Entity\KlientContact;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Klient
*
* #ORM\Table(name="klient")
* #ORM\Entity(repositoryClass="AdminBundle\Repository\KlientRepository")
* #ORM\HasLifecycleCallbacks
*/
class Klient
{
public function __construct()
{
$this->contacts = new ArrayCollection();
}
public function __toString() {
return "NIP: ".$this->nip .", NAZWA: ". $this->name .", TEL: ". $this->tel;
}
/**
* #var string
* #ORM\Id
* #ORM\Column(name="nip", type="string", length=255)
*
*/
private $nip;
/**
* #var string
*
* #ORM\Column(name="regon", type="string", length=255)
*/
private $regon;
/**
* #var \DateTime
* #ORM\Column(name="inserted_at", type="datetime", nullable=true)
*/
private $insertedAt;
/**
* #var \DateTime
* #ORM\Column(name="last_edited_at", type="datetime", nullable=true)
*/
private $lastEditedAt;
/**
* #var string
*
* #ORM\Column(name="krs", type="string", length=255)
*/
private $krs;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="tel", type="string", length=255, nullable=true)
*/
private $tel;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, nullable=true)
*/
private $email;
/**
* #var type
*
* #ORM\OneToMany(targetEntity="KlientContact", mappedBy="fkKlient")
*/
private $contacts; // optional properyty holds an array of contact objects - this is not a fild in database
/**
* Set nip
*
* #param string $nip
*
* #return Klient
*/
public function setNip($nip)
{
$this->nip = $nip;
return $this;
}
/**
* Get nip
*
* #return string
*/
public function getNip()
{
return $this->nip;
}
/**
* Set regon
*
* #param string $regon
*
* #return Klient
*/
public function setRegon($regon)
{
$this->regon = $regon;
return $this;
}
/**
* Get regon
*
* #return string
*/
public function getRegon()
{
return $this->regon;
}
/**
* Set krs
*
* #param string $krs
*
* #return Klient
*/
public function setKrs($krs)
{
$this->krs = $krs;
return $this;
}
/**
* Get krs
*
* #return string
*/
public function getKrs()
{
return $this->krs;
}
/**
* Set address
*
* #param string $address
*
* #return Klient
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set name
*
* #param string $name
*
* #return Klient
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set tel
*
* #param string $tel
*
* #return Klient
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set email
*
* #param string $email
*
* #return Klient
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Add contact
*
* #param \AdminBundle\Entity\KlientContact $contact
*
* #return Klient
*/
public function addContact(\AdminBundle\Entity\KlientContact $contact)
{
$this->contacts[] = $contact;
return $this;
}
/**
* Remove contact
*
* #param \AdminBundle\Entity\KlientContact $contact
*/
public function removeContact(\AdminBundle\Entity\KlientContact $contact)
{
$this->contacts->removeElement($contact);
}
/**
* Get contacts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContacts()
{
return $this->contacts;
}
/**
* Set insertedAt
*
* #param \DateTime $insertedAt
*
* #return Klient
*/
public function setInsertedAt(\DateTime $insertedAt)
{
$this->insertedAt = $insertedAt;
return $this;
}
/**
* Get insertedAt
*
* #return \DateTime
*/
public function getInsertedAt()
{
return $this->insertedAt;
}
/**
* Set lastEditedAt
*
* #param \DateTime $lastEditedAt
*
* #return Klient
*/
public function setLastEditedAt(\DateTime $lastEditedAt)
{
$this->lastEditedAt = $lastEditedAt;
return $this;
}
/**
* Get lastEditedAt
*
* #return \DateTime
*/
public function getLastEditedAt()
{
return $this->lastEditedAt;
}
/**
*
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updatedTimestamps()
{
$this->setLastEditedAt(new \DateTime('now'));
if ($this->getInsertedAt() == null) {
$this->setInsertedAt(new \DateTime('now'));
}
}
}
[KlientContact Entity]
<?php
namespace AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AdminBundle\Entity\Klient;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* KlientContact
*
* #ORM\Table(name="klient_contact")
* #ORM\Entity(repositoryClass="AdminBundle\Repository\KlientContactRepository")
* #ORM\HasLifecycleCallbacks
*/
class KlientContact implements UserInterface
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="inserted_at", type="datetime", nullable=true)
*/
private $insertedAt;
/**
* #var \DateTime
*
* #ORM\Column(name="last_edited_at", type="datetime", nullable=true)
*/
private $lastEditedAt;
/**
* #ORM\ManyToOne(targetEntity="Klient", inversedBy="nip")
* #ORM\JoinColumn(name="fk_klient", referencedColumnName="nip")
*/
private $fkKlient;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="surname", type="string", length=255)
*/
private $surname;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255)
*/
private $phone;
/**
* #var string
*
* #ORM\Column(name="login", type="string", length=255, unique=true)
*/
private $login;
/**
* #var string
*
* #ORM\Column(name="password", type="text")
*/
private $password;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return KlientContact
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* #param string $surname
*
* #return KlientContact
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set email
*
* #param string $email
*
* #return KlientContact
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set phone
*
* #param string $phone
*
* #return KlientContact
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set login
*
* #param string $login
*
* #return KlientContact
*/
public function setLogin($login)
{
$this->login = $login;
return $this;
}
/**
* Get login
*
* #return string
*/
public function getLogin()
{
return $this->login;
}
/**
* Set password
*
* #param string $password
*
* #return KlientContact
*/
public function setPassword($password)
{
$hash = password_hash($password, PASSWORD_BCRYPT , ['cost' => 5]);
$this->password = $hash;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set fkKlient
*
* #param \AdminBundle\Entity\Klient $fkKlient
*
* #return KlientContact
*/
public function setFkKlient(\AdminBundle\Entity\Klient $fkKlient = null)
{
$this->fkKlient = $fkKlient;
return $this;
}
/**
* Get fkKlient
*
* #return \AdminBundle\Entity\Klient
*/
public function getFkKlient()
{
return $this->fkKlient;
}
public function eraseCredentials() {
}
public function getRoles() {
return ['ROLE_USER'];
}
public function getSalt() {
return null;
}
public function getUsername() {
}
/**
* Set insertedAt
*
* #param \DateTime $insertedAt
*
* #return KlientContact
*/
public function setInsertedAt(\DateTime $insertedAt)
{
$this->insertedAt = $insertedAt;
return $this;
}
/**
* Get insertedAt
*
* #return \DateTime
*/
public function getInsertedAt()
{
return $this->insertedAt;
}
/**
* Set lastEditedAt
*
* #param \DateTime $lastEditedAt
*
* #return KlientContact
*/
public function setLastEditedAt(\DateTime $lastEditedAt)
{
$this->lastEditedAt = $lastEditedAt;
return $this;
}
/**
* Get lastEditedAt
*
* #return \DateTime
*/
public function getLastEditedAt()
{
return $this->lastEditedAt;
}
/**
*
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updatedTimestamps()
{
$this->setLastEditedAt(new \DateTime('now'));
if ($this->getInsertedAt() == null) {
$this->setInsertedAt(new \DateTime('now'));
}
}
}
The inverse side is wrong. Should be:
[KlientContact Entity]
/**
* #ORM\ManyToOne(targetEntity="Klient", inversedBy="contacts")
* #ORM\JoinColumn(name="fk_klient", referencedColumnName="nip")
*/
private $fkKlient;

count an attribute in an entity

I have an entity "user" that has OneToMany relation with the entity "vehicule". I'm trying to count the number of vehicules for each user. This is my function
$emm = $this->getDoctrine();
$directions = $emm->getRepository('OCUserBundle:User')->findAll();
foreach($directions as $direction) {
$direction->getVehicule()->count();
}
return $this->render('DemandevehBundle:Demande:affiche.html.twig', array('demandes' => $demandes
, ));
but how could I put it in the return so that i could use it in my affiche.html.twig. because I want to show foreach user the number of vehicules he have . Thanks a lot
This is my entity Vehicule
<?php
namespace Car\PfeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use OC\UserBundle\Entity\User;
/**
* Vehicule
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Car\PfeBundle\Entity\VehiculeRepository")
*/
class Vehicule
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="carte_grise", type="integer", unique=true)
*/
private $carteGrise;
/**
* #var string
*
* #ORM\Column(name="modele", type="string", length=255)
*/
private $modele;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=255)
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="categorie", type="string", length=255)
*/
private $categorie;
/**
* #var integer
*
* #ORM\Column(name="puissance", type="integer")
*
*/
private $puissance;
/**
* #var integer
*
* #ORM\Column(name="nb_place", type="integer")
*/
private $nbPlace;
/**
* #var integer
*
* #ORM\Column(name="kilometrage", type="integer")
*/
private $kilometrage;
/**
* #var string
*
* #ORM\Column(name="marque", type="string", length=255)
*/
private $marque;
/**
* #var string
*
* #ORM\Column(name="carburant", type="string", length=255)
*/
private $carburant;
/**
* #var string
*
* #ORM\Column(name="transmission", type="string", length=255)
*/
private $transmission;
/**
* #ORM\ManyToOne(targetEntity="OC\UserBundle\Entity\User", inversedBy="vehicule")
* #ORM\JoinColumn(name="User_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $direction;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Id
*
* #param integer $carteGrise
* #return Vehicule
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set carteGrise
*
* #param integer $carteGrise
* #return Vehicule
*/
public function setCarteGrise($carteGrise)
{
$this->carteGrise = $carteGrise;
return $this;
}
/**
* Get carteGrise
*
* #return integer
*/
public function getCarteGrise()
{
return $this->carteGrise;
}
/**
* Set modele
*
* #param string $modele
* #return Vehicule
*/
public function setModele($modele)
{
$this->modele = $modele;
return $this;
}
/**
* Get modele
*
* #return string
*/
public function getModele()
{
return $this->modele;
}
/**
* Set categorie
*
* #param string $categorie
* #return Vehicule
*/
public function setCategorie($categorie)
{
$this->categorie = $categorie;
return $this;
}
/**
* Get categorie
*
* #return string
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set puissance
*
* #param integer $puissance
* #return Vehicule
*/
public function setPuissance($puissance)
{
$this->puissance = $puissance;
return $this;
}
/**
* Get puissance
*
* #return integer
*/
public function getPuissance()
{
return $this->puissance;
}
/**
* Set nbPlace
*
* #param integer $nbPlace
* #return Vehicule
*/
public function setNbPlace($nbPlace)
{
$this->nbPlace = $nbPlace;
return $this;
}
/**
* Get nbPlace
*
* #return integer
*/
public function getNbPlace()
{
return $this->nbPlace;
}
/**
* Set kilometrage
*
* #param integer $kilometrage
* #return Vehicule
*/
public function setKilometrage($kilometrage)
{
$this->kilometrage = $kilometrage;
return $this;
}
/**
* Get kilometrage
*
* #return integer
*/
public function getKilometrage()
{
return $this->kilometrage;
}
/**
* Set marque
*
* #param string $marque
* #return Vehicule
*/
public function setMarque($marque)
{
$this->marque = $marque;
return $this;
}
/**
* Get marque
*
* #return string
*/
public function getMarque()
{
return $this->marque;
}
/**
* Set carburant
*
* #param string $carburant
* #return Vehicule
*/
public function setCarburant($carburant)
{
$this->carburant = $carburant;
return $this;
}
/**
* Get carburant
*
* #return string
*/
public function getCarburant()
{
return $this->carburant;
}
/**
* Set transmission
*
* #param string $transmission
* #return Vehicule
*/
public function setTransmission($transmission)
{
$this->transmission = $transmission;
return $this;
}
/**
* Get transmission
*
* #return string
*/
public function getTransmission()
{
return $this->transmission;
}
public function __toString()
{
return (string)$this->id;
}
/**
* Set type
*
* #param string $type
* #return Vehicule
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set direction
*
* #param \OC\UserBundle\Entity\User $direction
* #return Vehicule
*/
public function setDirection(\OC\UserBundle\Entity\User $direction = null)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return \OC\UserBundle\Entity\User
*/
public function getDirection()
{
return $this->direction;
}
}
and this is my entity User
<?php
namespace OC\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Car\PfeBundle\Entity\Vehicule;
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="OC\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="nomDirec", type="string", length=255, unique=true)
*/
private $nomDirec;
/**
* #var string
*
* #ORM\Column(name="directeur", type="string", length=255)
*/
private $directeur;
/**
* #var string
*
* #ORM\Column(name="adresse", type="string", length=255)
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="fax", type="integer")
*/
private $fax;
/**
* #var string
*
* #ORM\Column(name="tel", type="integer")
*/
private $tel;
/**
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #ORM\Column(name="roles", type="array")
*/
private $roles = array();
/**
* #ORM\OneToMany(targetEntity="Car\PfeBundle\Entity\Vehicule", mappedBy="direction", cascade={"remove", "persist"})
*/
protected $vehicule;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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;
}
/**
* Set roles
*
* #param array $roles
* #return User
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return array
*/
public function getRoles()
{
return $this->roles;
}
public function eraseCredentials()
{
}
/**
* Set nomDirec
*
* #param string $nomDirec
* #return User
*/
public function setNomDirec($nomDirec)
{
$this->nomDirec = $nomDirec;
return $this;
}
/**
* Get nomDirec
*
* #return string
*/
public function getNomDirec()
{
return $this->nomDirec;
}
/**
* Set directeur
*
* #param string $directeur
* #return User
*/
public function setDirecteur($directeur)
{
$this->directeur = $directeur;
return $this;
}
/**
* Get directeur
*
* #return string
*/
public function getDirecteur()
{
return $this->directeur;
}
/**
* Set adresse
*
* #param string $adresse
* #return User
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* 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 fax
*
* #param \integer $fax
* #return User
*/
public function setFax($fax)
{
$this->fax = $fax;
return $this;
}
/**
* Get fax
*
* #return \integer
*/
public function getFax()
{
return $this->fax;
}
/**
* Set tel
*
* #param integer $tel
* #return User
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return integer
*/
public function getTel()
{
return $this->tel;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
public function __toString()
{
return strval( $this->getId() );
}
/**
* Constructor
*/
public function __construct()
{
$this->vehicule = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add vehicule
*
* #param \Car\PfeBundle\Entity\Vehicule $vehicule
* #return User
*/
public function addVehicule(\Car\PfeBundle\Entity\Vehicule $vehicule)
{
$this->vehicule[] = $vehicule;
return $this;
}
/**
* Remove vehicule
*
* #param \Car\PfeBundle\Entity\Vehicule $vehicule
*/
public function removeVehicule(\Car\PfeBundle\Entity\Vehicule $vehicule)
{
$this->vehicule->removeElement($vehicule);
}
/**
* Get vehicule
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVehicule()
{
return $this->vehicule;
}
}
The correct way to do this in a OOP way , is to define a method that returns the number of vehicules foreach user, so you could to this:
define a getNumberOfVehicules function in your User Class 'Entity'
public function getNumberOfVehicules()
{
return $this->vehicule->count();
}
then in your twig template you just simply call that function , i.e:
{% for user in users %}
<p>{{user.username}} {{user.getNumberOfVehicules()}}</p>
{% endfor %}
to get the desired result, I would do something like this ( haven't tested the query, but it should pretty much work )
$em = $this->getDoctrine();
$userRepository = $em->getRepository('OCUserBundle:User');
$qb = $userRepository->createQueryBuilder('user')
->leftJoin('user.vehicule','vehicule')
->addSelect('COUNT(vehicule.id) AS vehicule_count')
->groupBy('user.id')
->getQuery();
$result = $qb->getResult();
Pass the result to the view
return $this->render('DemandevehBundle:Demande:affiche.html.twig',
array('demandes' => $result ));
In the view you can iterate over the results.
$qb = $this->getEntityManager()->createQueryBuilder();
return $qb->select('u.username as name, count(v.id) as count')
->from('OCUserBundle:User', 'u')
->leftJoin('u.vehicule', 'v')
->groupBy('u.id')
->getQuery()
->getResult();
Here we get an array as result with each user plus no of corresponding vehicles.Just pass result to twig and then foreach name and count.All the best.

symfony2 the target-entity OC\PlateformBundle\Entity\Image cannot be found in 'OC\PlatformBundle\Entity\Advert#image

I can't find the solution of the problem when I do the update : the target-entity OC\PlateformBundle\Entity\Image cannot be found in 'OC\PlatformBundle\Entity\Advert#image'.
The Advert.php :
<?php
namespace OC\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Advert
*
* #ORM\Table(name="oc_advert")
* #ORM\Entity(repositoryClass="OC\PlatformBundle\Entity\AdvertRepository")
*/
class Advert
{
public function __construct()
{
// Par défaut, la date de l'annonce est la date d'aujourd'hui
$this->date = new \Datetime();
}
/**
* #ORM\OneToOne(targetEntity="OC\PlatformBundle\Entity\Image", cascade={"persist"})
*/
private $image;
public function getImage()
{
return $this->image;
}
public function setImage(Image $image = null)
{
$this->image = $image;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Advert
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set title
*
* #param string $title
*
* #return Advert
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
*
* #return Advert
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set content
*
* #param string $content
*
* #return Advert
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* #ORM\Column(name="published", type="boolean")
*/
private $published = true;
/**
* Set published
*
* #param boolean $published
*
* #return Advert
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
}
I have looked for any uppercase ou lowercase problem... but none noticed.

How to use Doctrine2 getScheduledEntityUpdates()

BudgetItem is related as ManyToOne to Budget and to Product. Here are the 3 entities:
BudgetItem
<?php
namespace CDGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\Product;
/**
* BudgetItem
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\BudgetItemRepository")
* #ORM\HasLifecycleCallbacks
*/
class BudgetItem
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Product")
* #ORM\JoinColumn(nullable=false)
*/
private $product;
/**
* #var integer
*
* #ORM\Column(name="meters", type="integer")
*/
private $meters;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", scale=2)
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="Budget", inversedBy="items")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $budget;
/**
* To String
*
* #return string
*/
public function __toString()
{
return $this->getProduct()->getName();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set budget
*
* #param integer $budget
*
* #return BudgetItem
*/
public function setBudget(Budget $budget)
{
$this->budget = $budget;
return $this;
}
/**
* Get budget
*
* #return integer
*/
public function getBudget()
{
return $this->budget;
}
/**
* Set product
*
* #param integer $product
*
* #return BudgetItem
*/
public function setProduct(Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return integer
*/
public function getProduct()
{
return $this->product;
}
/**
* Set meters
*
* #param integer $meters
*
* #return BudgetItem
*/
public function setMeters($meters)
{
$this->meters = $meters;
return $this;
}
/**
* Get meters
*
* #return integer
*/
public function getMeters()
{
return $this->meters;
}
/**
* Set price
*
* #param string $price
*
* #return BudgetItem
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* #return integer;
*/
public function decreaseProductMeters()
{
return $this->getProduct()->getMeters() - $this->getMeters();
}
/**
* #ORM\PrePersist
*/
public function onPreEvents()
{
$this->getProduct()->setMeters($this->decreaseProductMeters());
}
public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityUpdates() as $entity) {
$entity->getProduct();
$em->persist($entity);
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
}
Budget
<?php
namespace CDGBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\Customer;
use CDGBundle\Entity\BudgetItem;
/**
* Budget
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\BudgetRepository")
* #ORM\HasLifecycleCallbacks
*/
class Budget
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\ManyToOne(targetEntity="Customer", inversedBy="budgets")
*/
private $customer;
/**
* #var integer
*
* #ORM\OneToMany(targetEntity="BudgetItem", mappedBy="budget", cascade={"persist"})
*/
private $items;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var integer
*
* #ORM\Column(name="installment_rate", type="integer")
*/
private $installmentRate;
/**
* #var integer
*
* #ORM\Column(name="check_for", type="integer")
*/
private $checkFor;
/**
* #var \DateTime
*
* #ORM\Column(name="starts_at", type="datetime", nullable=true)
*/
private $startsAt;
/**
* #var \DateTime
*
* #ORM\Column(name="deadline", type="datetime", nullable=true)
*/
private $deadline;
/**
* #var string
*
* #ORM\Column(name="is_approved", type="string", length=1, nullable=true)
*/
private $isApproved;
/**
* #var string
*
* #ORM\Column(name="has_started", type="string", length=1, nullable=true)
*/
private $hasStarted;
/**
* #var decimal
*
* #ORM\Column(name="installment_rate_price", type="decimal", scale=2, nullable=true)
*/
private $installmentRatePrice;
/**
* #var decimal
*
* #ORM\Column(name="total_budget_price", type="decimal", scale=2, nullable=true)
*/
private $totalBudgetPrice;
/**
* #var \DateTime
*
* #ORM\Column(name="next_payment_date", type="datetime", nullable=true)
*/
private $nextPaymentDate;
/**
* #var string
*
* #ORM\Column(name="is_paid", type="string", length=1)
*/
private $isPaid;
/**
* #var string
*
* #ORM\Column(name="obs", type="text", nullable=true)
*/
private $obs;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Constructor
*/
public function __construct()
{
$this->items = new ArrayCollection();
$this->createdAt = new \DateTime();
$this->isPaid = 'n';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set address
*
* #param string $address
*
* #return Budget
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set installmentRate
*
* #param integer $installmentRate
*
* #return Budget
*/
public function setInstallmentRate($installmentRate)
{
$this->installmentRate = $installmentRate;
return $this;
}
/**
* Get installmentRate
*
* #return integer
*/
public function getInstallmentRate()
{
return $this->installmentRate;
}
/**
* Set checkFor
*
* #param integer $checkFor
*
* #return Budget
*/
public function setCheckFor($checkFor)
{
$this->checkFor = $checkFor;
return $this;
}
/**
* Get checkFor
*
* #return integer
*/
public function getCheckFor()
{
return $this->checkFor;
}
/**
* Set startsAt
*
* #param \DateTime $startsAt
*
* #return Budget
*/
public function setStartsAt($startsAt)
{
$this->startsAt = $startsAt;
return $this;
}
/**
* Get startsAt
*
* #return \DateTime
*/
public function getStartsAt()
{
return $this->startsAt;
}
/**
* Set deadline
*
* #param \DateTime $deadline
*
* #return Budget
*/
public function setDeadline($deadline)
{
$this->deadline = $deadline;
return $this;
}
/**
* Get deadline
*
* #return \DateTime
*/
public function getDeadline()
{
return $this->deadline;
}
/**
* Set isApproved
*
* #param string $isApproved
*
* #return Budget
*/
public function setIsApproved($isApproved)
{
$this->isApproved = $isApproved;
return $this;
}
/**
* Get isApproved
*
* #return string
*/
public function getIsApproved()
{
return $this->isApproved;
}
/**
* Set hasStarted
*
* #param string $hasStarted
*
* #return Budget
*/
public function setHasStarted($hasStarted)
{
$this->hasStarted = $hasStarted;
return $this;
}
/**
* Get hasStarted
*
* #return string
*/
public function getHasStarted()
{
return $this->hasStarted;
}
/**
* Set installmentRatePrice
*
* #param string $installmentRatePrice
*
* #return Budget
*/
public function setInstallmentRatePrice($installmentRatePrice)
{
$this->installmentRatePrice = $installmentRatePrice;
return $this;
}
/**
* Get installmentRatePrice
*
* #return string
*/
public function getInstallmentRatePrice()
{
return $this->installmentRatePrice;
}
/**
* Set totalBudgetPrice
*
* #param string $totalBudgetPrice
*
* #return Budget
*/
public function setTotalBudgetPrice($totalBudgetPrice)
{
$this->totalBudgetPrice = $totalBudgetPrice;
return $this;
}
/**
* Get totalBudgetPrice
*
* #return string
*/
public function getTotalBudgetPrice()
{
return $this->totalBudgetPrice;
}
/**
* Set nextPaymentDate
*
* #param \DateTime $nextPaymentDate
*
* #return Budget
*/
public function setNextPaymentDate($nextPaymentDate)
{
$this->nextPaymentDate = $nextPaymentDate;
return $this;
}
/**
* Get nextPaymentDate
*
* #return \DateTime
*/
public function getNextPaymentDate()
{
return $this->nextPaymentDate;
}
/**
* Set isPaid
*
* #param string $isPaid
*
* #return Budget
*/
public function setIsPaid($isPaid)
{
$this->isPaid = $isPaid;
return $this;
}
/**
* Get isPaid
*
* #return string
*/
public function getIsPaid()
{
return $this->isPaid;
}
/**
* Set obs
*
* #param string $obs
*
* #return Budget
*/
public function setObs($obs)
{
$this->obs = $obs;
return $this;
}
/**
* Get obs
*
* #return string
*/
public function getObs()
{
return $this->obs;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Budget
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set customer
*
* #param Customer $customer
*
* #return Budget
*/
public function setCustomer(Customer $customer = null)
{
$this->customer = $customer;
return $this;
}
/**
* Get customer
*
* #return Customer
*/
public function getCustomer()
{
return $this->customer;
}
/**
* Add item
*
* #param BudgetItem $item
*
* #return Budget
*/
public function addItem(BudgetItem $item)
{
$item->setBudget($this);
$this->items->add($item);
return $this;
}
/**
* Remove item
*
* #param BudgetItem $item
*/
public function removeItem(BudgetItem $item)
{
$this->items->removeElement($item);
}
/**
* Get items
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getItems()
{
return $this->items;
}
/**
* #return \DateTime
*/
public function generateNextPaymentDate()
{
if ($this->getStartsAt() !== null) {
$date = new \DateTime($this->getStartsAt()->format('Y-m-d'));
return $date->add(new \DateInterval('P' . $this->getCheckFor() . 'D'));
}
}
/**
* #return decimal
*/
public function calculateTotalBudgetPrice()
{
$totalBudgetPrice = 0;
foreach ($this->getItems() as $item) {
$totalBudgetPrice += $item->getPrice();
}
return $totalBudgetPrice;
}
/**
* #return decimal
*/
public function calculateInstallmentRatePrice()
{
return $this->calculateTotalBudgetPrice() / $this->getInstallmentRate();
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function onPreEvents()
{
$this->setNextPaymentDate($this->generateNextPaymentDate());
$this->setInstallmentRatePrice($this->calculateInstallmentRatePrice());
$this->setTotalBudgetPrice($this->calculateTotalBudgetPrice());
}
}
Product
<?php
namespace CDGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use CDGBundle\Entity\ProductType;
/**
* Product
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="CDGBundle\Entity\Repository\ProductRepository")
* #ORM\HasLifecycleCallbacks
*/
class Product
{
/**
* #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)
*/
private $name;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="ProductType")
* #ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", scale=2)
*/
private $price;
/**
* #var integer
*
* #ORM\Column(name="meters", type="integer", nullable=true)
*/
private $meters;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Constructor
*/
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* To String
*
* #return string
*/
public function __toString()
{
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set type
*
* #param \CDGBundle\Entity\ProductType $type
*
* #return Product
*/
public function setType(ProductType $type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return \CDGBundle\Entity\ProductType
*/
public function getType()
{
return $this->type;
}
/**
* Set price
*
* #param string $price
*
* #return Product
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set meters
*
* #param integer $meters
*
* #return Product
*/
public function setMeters($meters)
{
$this->meters = $meters;
return $this;
}
/**
* Get meters
*
* #return integer
*/
public function getMeters()
{
return $this->meters;
}
/**
* Set description
*
* #param string $description
*
* #return Product
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Product
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}
Product is a collection form inside of Budget. It lists all the registered products to choose when registering a new budget. I have all the necessary JavaScript and a macro to show the form.
I need to update the total amount of meters from Product entity when EDITING an existing Budget. I have an onFlush method inside of BudgetItem for this:
public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityUpdates() as $entity) {
$entity->getItems();
$em->persist($entity);
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
Now here is my problem. I do not know what to do inside of the foreach method. I need to do the same as I do in the PrePersist method, but I get different errors.
Inside of the loop, if I do $entity->getItems(), I get the error:
Attempted to call an undefined method named "getItems" of class "CDGBundle\Entity\BudgetItem".
If I do $entity->getProduct(), the error:
Attempted to call an undefined method named "getProduct" of class "CDGBundle\Entity\Budget".
Why does it magically change the entity? For God sake someone help me with this. Doctrine2 has a too complicated updating event.
In a Doctrine listener, you always need to check the class of the entity, since every single updated items are stored in your getScheduledEntityUpdates() method.
The solution is to test if updated entity is an instance of Budget:
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if ($entity instanceof Budget) {
// $entity is a Budget entity
// ... your code here
}
}

#Assert\Valid of OneToMany property doesn't work

I'm trying to solve my problem but after many hours of search, It doesn't work :(
So I've got a class :
<?php
namespace Application\HappyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Bar
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Application\HappyBundle\Entity\BarRepository")
*/
class Bar
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="name", type="string", length=45)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="addressComplete", type="string", length=255)
*/
private $addressComplete;
/**
* #var string
*
* #ORM\Column(name="postal_code", type="string", length=5, nullable=true)
*/
private $postalCode;
/**
* #var string
*
* #ORM\Column(name="town", type="string", length=45)
*/
private $town;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=45)
*/
private $country;
/**
* #var string
*
* #ORM\Column(name="latitude", type="string", length=20)
*/
private $latitude;
/**
* #var string
*
* #ORM\Column(name="longitude", type="string", length=20)
*/
private $longitude;
/**
* #var array
*
* #ORM\Column(name="validate", type="boolean", nullable=false)
*/
private $validate;
/**
* #var \DateTime
*
* #ORM\Column(name="last_update", type="datetime", nullable=true)
*/
private $lastUpdate;
/**
* #var ArrayCollection of AssocBarDay
* #Assert\Valid
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\AssocBarDay", mappedBy="bar" , cascade={"persist" , "remove"})
*/
private $day;
/**
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\AssocBarDrink", mappedBy="drink", cascade={"persist"})
*/
private $drink;
/**
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\Bar", mappedBy="barVersionned", cascade={"persist"})
*/
private $barHaveVersions;
/**
* #ORM\ManyToOne(targetEntity="Application\HappyBundle\Entity\Bar", inversedBy="barHaveVersions" , cascade={"persist"})
*/
private $barVersionned;
/**
* Constructor
*/
public function __construct()
{
$this->day = new \Doctrine\Common\Collections\ArrayCollection();
$this->drink = new \Doctrine\Common\Collections\ArrayCollection();
$this->validate = false;
$this->lastUpdate = new \DateTime('now');
}
public function __toString(){
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Bar
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
* #return Bar
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set postalCode
*
* #param string $postalCode
* #return Bar
*/
public function setPostalCode($postalCode)
{
$this->postalCode = $postalCode;
return $this;
}
/**
* Get postalCode
*
* #return string
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* Set town
*
* #param string $town
* #return Bar
*/
public function setTown($town)
{
$this->town = $town;
return $this;
}
/**
* Get town
*
* #return string
*/
public function getTown()
{
return $this->town;
}
/**
* Set country
*
* #param string $country
* #return Bar
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set latitude
*
* #param string $latitude
* #return Bar
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* #return string
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* #param string $longitude
* #return Bar
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* #return string
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Add drink
*
* #param \Application\HappyBundle\Entity\AssocBarDrink $drink
* #return Bar
*/
public function addDrink(\Application\HappyBundle\Entity\AssocBarDrink $drink)
{
$this->drink[] = $drink;
return $this;
}
/**
* Remove drink
*
* #param \Application\HappyBundle\Entity\AssocBarDrink $drink
*/
public function removeDrink(\Application\HappyBundle\Entity\AssocBarDrink $drink)
{
$this->drink->removeElement($drink);
}
/**
* Get drink
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDrink()
{
return $this->drink;
}
/**
* Add day
*
* #param \Application\HappyBundle\Entity\AssocBarDay $day
* #return Bar
*/
public function addDay(\Application\HappyBundle\Entity\AssocBarDay $day)
{
$this->day[] = $day;
return $this;
}
/**
* Remove day
*
* #param \Application\HappyBundle\Entity\AssocBarDay $day
*/
public function removeDay(\Application\HappyBundle\Entity\AssocBarDay $day)
{
$this->day->removeElement($day);
}
/**
* Get day
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDay()
{
return $this->day;
}
/**
* Set lastUpdate
*
* #param \DateTime $lastUpdate
* #return Bar
*/
public function setLastUpdate($lastUpdate)
{
$this->lastUpdate = $lastUpdate;
return $this;
}
/**
* Get lastUpdate
*
* #return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* Set validate
*
* #param boolean $validate
* #return Bar
*/
public function setValidate($validate)
{
$this->validate = $validate;
return $this;
}
/**
* Get validate
*
* #return boolean
*/
public function getValidate()
{
return $this->validate;
}
/**
* Add barHaveVersions
*
* #param \Application\HappyBundle\Entity\Bar $barHaveVersions
* #return Bar
*/
public function addBarHaveVersion(\Application\HappyBundle\Entity\Bar $barHaveVersions)
{
$this->barHaveVersions[] = $barHaveVersions;
return $this;
}
/**
* Remove barHaveVersions
*
* #param \Application\HappyBundle\Entity\Bar $barHaveVersions
*/
public function removeBarHaveVersion(\Application\HappyBundle\Entity\Bar $barHaveVersions)
{
$this->barHaveVersions->removeElement($barHaveVersions);
}
/**
* Get barHaveVersions
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBarHaveVersions()
{
return $this->barHaveVersions;
}
/**
* Set barVersionned
*
* #param \Application\HappyBundle\Entity\Bar $barVersionned
* #return Bar
*/
public function setBarVersionned(\Application\HappyBundle\Entity\Bar $barVersionned = null)
{
$this->barVersionned = $barVersionned;
return $this;
}
/**
* Get barVersionned
*
* #return \Application\HappyBundle\Entity\Bar
*/
public function getBarVersionned()
{
return $this->barVersionned;
}
/**
* Set addressComplete
*
* #param string $addressComplete
* #return Bar
*/
public function setAddressComplete($addressComplete)
{
$this->addressComplete = $addressComplete;
return $this;
}
/**
* Get addressComplete
*
* #return string
*/
public function getAddressComplete()
{
return $this->addressComplete;
}
}
and OneToMany with this class:
<?php
namespace Application\HappyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* AssocBarDayHappyHour
* #ORM\Table(name="assoc_bar_day")
* #ORM\Entity(repositoryClass="Application\HappyBundle\Entity\AssocBarDayRepository")
*/
class AssocBarDay
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Application\HappyBundle\Entity\Bar", inversedBy="day" , cascade={"persist"})
*/
private $bar;
/**
* #var array
* #ORM\Column(name="day", type="array", nullable=true)
*/
private $day;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_start_happy_hour", type="time", nullable=true)
*/
private $timeStartHappyHour;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_end_happy_hour", type="time", nullable=true)
*/
private $timeEndHappyHour;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_bar_open", type="time", nullable=true)
*/
private $timeBarOpen;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_bar_close", type="time" , nullable=true)
*/
private $timeBarClose;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set timeStartHappyHour
*
* #param \DateTime $timeStartHappyHour
* #return AssocBarDay
*/
public function setTimeStartHappyHour($timeStartHappyHour)
{
$this->timeStartHappyHour = $timeStartHappyHour;
return $this;
}
/**
* Get timeStartHappyHour
*
* #return \DateTime
*/
public function getTimeStartHappyHour()
{
return $this->timeStartHappyHour;
}
/**
* Set timeEndHappyHour
*
* #param \DateTime $timeEndHappyHour
* #return AssocBarDay
*/
public function setTimeEndHappyHour($timeEndHappyHour)
{
$this->timeEndHappyHour = $timeEndHappyHour;
return $this;
}
/**
* Get timeEndHappyHour
*
* #return \DateTime
*/
public function getTimeEndHappyHour()
{
return $this->timeEndHappyHour;
}
/**
* Set timeBarOpen
*
* #param \DateTime $timeBarOpen
* #return AssocBarDay
*/
public function setTimeBarOpen($timeBarOpen)
{
$this->timeBarOpen = $timeBarOpen;
return $this;
}
/**
* Get timeBarOpen
*
* #return \DateTime
*/
public function getTimeBarOpen()
{
return $this->timeBarOpen;
}
/**
* Set timeBarClose
*
* #param \DateTime $timeBarClose
* #return AssocBarDay
*/
public function setTimeBarClose($timeBarClose)
{
$this->timeBarClose = $timeBarClose;
return $this;
}
/**
* Get timeBarClose
*
* #return \DateTime
*/
public function getTimeBarClose()
{
return $this->timeBarClose;
}
/**
* Set bar
*
* #param \Application\HappyBundle\Entity\Bar $bar
* #return AssocBarDay
*/
public function setBar(\Application\HappyBundle\Entity\Bar $bar = null)
{
$this->bar = $bar;
return $this;
}
/**
* Get bar
*
* #return \Application\HappyBundle\Entity\Bar
*/
public function getBar()
{
return $this->bar;
}
/**
* Set day
*
* #param array $day
* #return AssocBarDay
*/
public function setDay($day)
{
$this->day = $day;
return $this;
}
/**
* Get day
*
* #return array
*/
public function getDay()
{
return $this->day;
}
}
So when I post my form, the Assert of the Collection of days doesn't block when time is empty?
I put correctly the:
#Assert\Valid
Over day Collection and
#Assert\Time()
of each property of AssocBarDay
:( anyone I've got an idea?
Thanks for your help.
The reason is almost all of the validation constraints will not return invalid for empty/null values.
Just have a look at the TimeValidator's validate method ...
if (null === $value || '' === $value || $value instanceof \DateTime) {
return;
}
Therefore you will need to add the #Assert\NotBlank constraint additionally to have empty values generate a validation error for that property.
NotBlank
Validates that a value is not blank, defined as not equal to a blank
string and also not equal to null.

Resources