Error on update query symfony2 - symfony

I generated the CRUD for the entity Evenement(event) , which is working. But now I want to update a field in another entity called notification everytime an Evenement is added. Each Evenement has a categorie
Evenement.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Mql14\mqlmeBundle\Entity\Evenement
*
* #ORM\Table(name="evenement")
* #ORM\Entity
*/
class Evenement
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=45, nullable=true)
*/
private $nom;
/**
* #var datetime $date
*
* #ORM\Column(name="date", type="datetime", nullable=true)
*/
private $date;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=400, nullable=true)
*/
private $description;
/**
* #var integer $ticket
*
* #ORM\Column(name="Ticket", type="integer", nullable=true)
*/
private $ticket;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="evenement")
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie", inversedBy="evenement")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="categorie_id", referencedColumnName="id")
* })
*/
private $categorie;
/**
* #var Lieu
*
* #ORM\ManyToOne(targetEntity="Lieu")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="lieu_id", referencedColumnName="id")
* })
*/
private $lieu;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set date
*
* #param datetime $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* Get date
*
* #return datetime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set ticket
*
* #param integer $ticket
*/
public function setTicket($ticket)
{
$this->ticket = $ticket;
}
/**
* Get ticket
*
* #return integer
*/
public function getTicket()
{
return $this->ticket;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set lieu
*
* #param Mql14\mqlmeBundle\Entity\Lieu $lieu
*/
public function setLieu(\Mql14\mqlmeBundle\Entity\Lieu $lieu)
{
$this->lieu = $lieu;
}
/**
* Get lieu
*
* #return Mql14\mqlmeBundle\Entity\Lieu
*/
public function getLieu()
{
return $this->lieu;
}
public function getCategorieId(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$idc= $categorie->getId();
return $idc;
}
}
Categorie.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity
*/
class Categorie
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nomcat
*
* #ORM\Column(name="nomCat", type="string", length=45, nullable=true)
*/
private $nomcat;
/**
* #var string $photo
*
* #ORM\Column(name="photo", type="string", length=45, nullable=true)
*/
private $photo;
/**
* #var $evenement
*
* #ORM\OneToMany(targetEntity="Evenement", mappedBy="categorie")
*/
private $evenement;
/**
* #var User
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="categorie")
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nomcat
*
* #param string $nomcat
*/
public function setNomcat($nomcat)
{
$this->nomcat = $nomcat;
}
/**
* Get nomcat
*
* #return string
*/
public function getNomcat()
{
return $this->nomcat;
}
/**
* Set photo
*
* #param string $photo
*/
public function setPhoto($photo)
{
$this->photo = $photo;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Add user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function addUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Add evenement
*
* #param Mql14\mqlmeBundle\Entity\Categorie $evenement
*/
public function addEvenement(\Mql14\mqlmeBundle\Entity\Evenement $evenement)
{
$this->evenement[] = $evenement;
}
/**
* Get evenement
*
* #return Doctrine\Common\Collections\Collection
*/
public function getEvenement()
{
return $this->evenement;
}
}
Notification.php:
<?php
namespace Mql14\mqlmeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mql14\mqlmeBundle\Entity\Notification
*
* #ORM\Table(name="notification")
* #ORM\Entity
*/
class Notification
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $etat
*
* #ORM\Column(name="etat", type="integer", nullable=true)
*/
private $etat;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="User_id", referencedColumnName="id")
*
* })
*/
private $user;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="Categorie_id", referencedColumnName="id")
*
* })
*/
private $categorie;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set etat
*
* #param string $etat
*/
public function setEtat($etat)
{
$this->etat = $etat;
}
/**
* Get etat
*
* #return string
*/
public function getEtat()
{
return $this->etat;
}
/**
* Set user
*
* #param Mql14\mqlmeBundle\Entity\User $user
*/
public function setUser(\Mql14\mqlmeBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return Mql14\mqlmeBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set categorie
*
* #param Mql14\mqlmeBundle\Entity\Categorie $categorie
*/
public function setCategorie(\Mql14\mqlmeBundle\Entity\Categorie $categorie)
{
$this->categorie = $categorie;
}
/**
* Get categorie
*
* #return Mql14\mqlmeBundle\Entity\Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
}
In the createAction that was generated after the execution of the CRUD for the Evenement entity I added the update query :
public function createAction(Request $request)
{
$entity = new Evenement();
$request = $this->getRequest();
$form = $this->createForm(new EvenementType(), $entity);
$form->bindRequest($request);
$entity->upload();
$cat=$entity->getCategorie();
if ($cat) {
$catn = $cat->getNomCat();
$query = $this->container->get('doctrine')->getEntityManager()->createQuery( 'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn ' );
$query->setParameter('categorie', $catn);
$query->execute();
}
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('mql14mqlme_adminshow', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
And the error I'm getting is this:
[Semantical Error] line 0, col 61 near 'categorie LIKE': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.

You set the wrong parameter in the update query.
On this line:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('categorie', $catn);
$query->execute();
It should be:
$query = $this->container->get('doctrine')->getEntityManager()->createQuery(
'UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1
WHERE n.categorie LIKE :catn' );
$query->setParameter('catn', $catn);
$query->execute();

n.categorie is an entity (of type Mql14\mqlmeBundle\Entity\Categorie) and you can't compare entities using LIKE.
Try replacing LIKE with =.
Change
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie LIKE :catn
To
UPDATE Mql14mqlmeBundle:Notification n SET n.etat=1 WHERE n.categorie = :catn

Related

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.

'Error: Invalid PathExpression. Must be a StateFieldPathExpression' Error in doctrine

I'm trying to join two tables and take a column value with doctrine query builder.
This is my code
public function getLatestProduct($amount) {
$em = $this->container->get('doctrine.orm.entity_manager');
$qb = $em->createQueryBuilder();
$qb->select('p.id, p.category, p.productTitle, p.price, p.description, pi.imgUrl')
->from('EagleShopBundle:Products', 'p')
->leftJoin('EagleShopBundle:ProuctImage', 'pi', \Doctrine\ORM\Query\Expr\Join::WITH, 'pi.productId = p.id')
->orderBy('p.id', 'DESC')
->groupBy('p.id')
->setMaxResults($amount);
return $qb->getQuery()->getResult();
}
This is where I call it
public function indexAction() {
$latest = $this->getLatestProduct(8);
$isfeatured = $this->getfeaturedProduct(8);
return $this->render("EagleShopBundle:global:home.html.twig", array(
'image_path' => '/bundles/eagleshop/images/',
'latest_products' => $latest,
'isfeatured' => $isfeatured
));
}
But when I try to call this method I'm having this issue,
[Semantical Error] line 0, col 15 near 'category, p.productTitle,':
Error: Invalid PathExpression. Must be a StateFieldPathExpression.
I think this code is related to the issue,
$qb->select('p.id, p.category, p.productTitle, p.price, p.description,
pi.imgUrl')
This is my Product entity
<?php
namespace Eagle\ShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Products
*
* #ORM\Table(name="products", indexes={#ORM\Index(name="category", columns={"category"})})
* #ORM\Entity
*/
class Products
{
/**
* #var string
*
* #ORM\Column(name="product_title", type="string", length=400, nullable=false)
*/
private $productTitle;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=400, nullable=false)
*/
private $description;
/**
* #var float
*
* #ORM\Column(name="price", type="float", precision=10, scale=0, nullable=false)
*/
private $price;
/**
* #var integer
*
* #ORM\Column(name="store_id", type="integer", nullable=false)
*/
private $storeId;
/**
* #var integer
*
* #ORM\Column(name="status", type="integer", nullable=false)
*/
private $status;
/**
* #var integer
*
* #ORM\Column(name="stock", type="integer", nullable=false)
*/
private $stock;
/**
* #var integer
*
* #ORM\Column(name="isfeatured", type="integer", nullable=false)
*/
private $isfeatured;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false)
*/
private $updatedAt;
/**
* #var integer
*
* #ORM\Column(name="online", type="integer", nullable=false)
*/
private $online;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Eagle\ShopBundle\Entity\ProductCategory
*
* #ORM\ManyToOne(targetEntity="Eagle\ShopBundle\Entity\ProductCategory")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category", referencedColumnName="id")
* })
*/
private $category;
/**
* Set productTitle
*
* #param string $productTitle
* #return Products
*/
public function setProductTitle($productTitle)
{
$this->productTitle = $productTitle;
return $this;
}
/**
* Get productTitle
*
* #return string
*/
public function getProductTitle()
{
return $this->productTitle;
}
/**
* Set description
*
* #param string $description
* #return Products
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set price
*
* #param float $price
* #return Products
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set storeId
*
* #param integer $storeId
* #return Products
*/
public function setStoreId($storeId)
{
$this->storeId = $storeId;
return $this;
}
/**
* Get storeId
*
* #return integer
*/
public function getStoreId()
{
return $this->storeId;
}
/**
* Set status
*
* #param integer $status
* #return Products
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set stock
*
* #param integer $stock
* #return Products
*/
public function setStock($stock)
{
$this->stock = $stock;
return $this;
}
/**
* Get stock
*
* #return integer
*/
public function getStock()
{
return $this->stock;
}
/**
* Set isfeatured
*
* #param integer $isfeatured
* #return Products
*/
public function setIsfeatured($isfeatured)
{
$this->isfeatured = $isfeatured;
return $this;
}
/**
* Get isfeatured
*
* #return integer
*/
public function getIsfeatured()
{
return $this->isfeatured;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Products
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Products
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set online
*
* #param integer $online
* #return Products
*/
public function setOnline($online)
{
$this->online = $online;
return $this;
}
/**
* Get online
*
* #return integer
*/
public function getOnline()
{
return $this->online;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category
*
* #param \Eagle\ShopBundle\Entity\ProductCategory $category
* #return Products
*/
public function setCategory(\Eagle\ShopBundle\Entity\ProductCategory $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Eagle\ShopBundle\Entity\ProductCategory
*/
public function getCategory()
{
return $this->category;
}
}

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
}
}

Doctrine persist entity with inverse relation not work

I'm trying to save two entities linked. Product entity may have any or many entities ProviderRate. When I try to save the product entity, it tells me that ProviderRate related entity has not assigned one of their required fields. I need to save a product with no need to assign a ProviderRate.
The error message showing me is:
Entity of type AppBundle\Entity\ProviderRate is missing an assigned ID for field 'provider'.
The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called.
If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
My entitdades code is as follows:
Product Entity
/**
* Products
*
* #ORM\Table(name="products", uniqueConstraints={#ORM\UniqueConstraint(name="id_producto_UNIQUE", columns={"id"})}, indexes={#ORM\Index(name="fk_id_productos_id_categorias1_idx", columns={"category_id"}), #ORM\Index(name="fk_id_productos_id_producto_tipo1_idx", columns={"type"}), #ORM\Index(name="fk_id_productos_id_moneda1_idx", columns={"currency_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProductsRepository")
*/
class Products {
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
* #Assert\NotBlank(message="Por favor, escriba el nombre del producto.")
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=45, nullable=false)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="description_long", type="text", nullable=false)
*/
private $descriptionLong;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=false)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="weight", type="decimal", precision=11, scale=3, nullable=false)
*/
private $weight;
/**
* #var string
*
* #ORM\Column(name="web", type="string", length=100, nullable=false)
*/
private $web;
/**
* #var boolean
*
* #ORM\Column(name="isActive", type="boolean", nullable=false)
*/
private $isactive;
/**
* #var \DateTime
*
* #ORM\Column(name="createdtime", type="datetime", nullable=false)
* #Assert\DateTime()
*/
private $createdtime;
/**
* #var \DateTime
*
* #ORM\Column(name="modifiedtime", type="datetime", nullable=false)
* #Assert\DateTime()
*/
private $modifiedtime;
/**
* #var \DateTime
*
* #ORM\Column(name="deletedtime", type="datetime", nullable=true)
*/
private $deletedtime;
/**
* #var boolean
*
* #ORM\Column(name="isDeleted", type="boolean", nullable=false)
*/
private $isdeleted;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \AppBundle\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \AppBundle\Entity\ProductTypes
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\ProductTypes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="type", referencedColumnName="id")
* })
*/
private $type;
/**
* #var \AppBundle\Entity\Currencies
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Currencies")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="currency_id", referencedColumnName="id")
* })
*/
private $currency;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Sets", inversedBy="product")
* #ORM\JoinTable(name="products_sets",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="set_id", referencedColumnName="id")
* }
* )
*/
private $set;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Products", mappedBy="productParentid")
*/
private $product;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Documents", inversedBy="product")
* #ORM\JoinTable(name="product_attachments",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
* }
* )
*/
private $document;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Images", inversedBy="product")
* #ORM\JoinTable(name="products_images",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="image_id", referencedColumnName="id")
* }
* )
*/
private $image;
// CUSTOM CODE
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\ProviderRate", mappedBy="product", cascade={"persist"})
*/
private $providerRate;
/**
* Constructor
*/
public function __construct() {
$this->createdtime = new \DateTime();
$this->modifiedtime = new \DateTime();
$this->set = new \Doctrine\Common\Collections\ArrayCollection();
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
$this->document = new \Doctrine\Common\Collections\ArrayCollection();
$this->image = new \Doctrine\Common\Collections\ArrayCollection();
$this->providerRate = new \Doctrine\Common\Collections\ArrayCollection();
$this->descriptionLong = '';
$this->amountPerUnit = 1;
$this->web = '';
$this->weight = 0;
$this->isdeleted = 0;
}
/**
* Set name
*
* #param string $name
* #return Products
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Products
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* Set code
*
* #param string $code
* #return Products
*/
public function setCode($code) {
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode() {
return $this->code;
}
/**
* Set descriptionLong
*
* #param string $descriptionLong
* #return Products
*/
public function setDescriptionLong($descriptionLong) {
$this->descriptionLong = $descriptionLong;
return $this;
}
/**
* Get descriptionLong
*
* #return string
*/
public function getDescriptionLong() {
return $this->descriptionLong;
}
/**
* Set amountPerUnit
*
* #param integer $amountPerUnit
* #return Products
*/
public function setAmountPerUnit($amountPerUnit) {
$this->amountPerUnit = $amountPerUnit;
return $this;
}
/**
* Get amountPerUnit
*
* #return integer
*/
public function getAmountPerUnit() {
return $this->amountPerUnit;
}
/**
* Set weight
*
* #param string $weight
* #return Products
*/
public function setWeight($weight) {
$this->weight = $weight;
return $this;
}
/**
* Get weight
*
* #return string
*/
public function getWeight() {
return $this->weight;
}
/**
* Set web
*
* #param string $web
* #return Products
*/
public function setWeb($web) {
$this->web = $web;
return $this;
}
/**
* Get web
*
* #return string
*/
public function getWeb() {
return $this->web;
}
/**
* Set isactive
*
* #param boolean $isactive
* #return Products
*/
public function setIsactive($isactive) {
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return boolean
*/
public function getIsactive() {
return $this->isactive;
}
/**
* Set createdtime
*
* #param \DateTime $createdtime
* #return Products
*/
public function setCreatedtime($createdtime) {
$this->createdtime = $createdtime;
return $this;
}
/**
* Get createdtime
*
* #return \DateTime
*/
public function getCreatedtime() {
return $this->createdtime;
}
/**
* Set modifiedtime
*
* #param \DateTime $modifiedtime
* #return Products
*/
public function setModifiedtime($modifiedtime) {
$this->modifiedtime = $modifiedtime;
return $this;
}
/**
* Get modifiedtime
*
* #return \DateTime
*/
public function getModifiedtime() {
return $this->modifiedtime;
}
/**
* Set deletedtime
*
* #param \DateTime $deletedtime
* #return Products
*/
public function setDeletedtime($deletedtime) {
$this->deletedtime = $deletedtime;
return $this;
}
/**
* Get deletedtime
*
* #return \DateTime
*/
public function getDeletedtime() {
return $this->deletedtime;
}
/**
* Set isdeleted
*
* #param boolean $isdeleted
* #return Products
*/
public function setIsdeleted($isdeleted) {
$this->isdeleted = $isdeleted;
return $this;
}
/**
* Get isdeleted
*
* #return boolean
*/
public function getIsdeleted() {
return $this->isdeleted;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set category
*
* #param \AppBundle\Entity\Categories $category
* #return Products
*/
public function setCategory(\AppBundle\Entity\Categories $category = null) {
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Categories
*/
public function getCategory() {
return $this->category;
}
/**
* Set type
*
* #param \AppBundle\Entity\ProductTypes $type
* #return Products
*/
public function setType(\AppBundle\Entity\ProductTypes $type = null) {
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return \AppBundle\Entity\ProductTypes
*/
public function getType() {
return $this->type;
}
/**
* Set currency
*
* #param \AppBundle\Entity\Currencies $currency
* #return Products
*/
public function setCurrency(\AppBundle\Entity\Currencies $currency = null) {
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return \AppBundle\Entity\Currencies
*/
public function getCurrency() {
return $this->currency;
}
/**
* Add set
*
* #param \AppBundle\Entity\Sets $set
* #return Products
*/
public function addSet(\AppBundle\Entity\Sets $set) {
$this->set[] = $set;
return $this;
}
/**
* Remove set
*
* #param \AppBundle\Entity\Sets $set
*/
public function removeSet(\AppBundle\Entity\Sets $set) {
$this->set->removeElement($set);
}
/**
* Get set
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSet() {
return $this->set;
}
/**
* Add product
*
* #param \AppBundle\Entity\Products $product
* #return Products
*/
public function addProduct(\AppBundle\Entity\Products $product) {
$this->product[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Products $product
*/
public function removeProduct(\AppBundle\Entity\Products $product) {
$this->product->removeElement($product);
}
/**
* Get product
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProduct() {
return $this->product;
}
/**
* Add document
*
* #param \AppBundle\Entity\Documents $document
* #return Products
*/
public function addDocument(\AppBundle\Entity\Documents $document) {
$this->document[] = $document;
return $this;
}
/**
* Remove document
*
* #param \AppBundle\Entity\Documents $document
*/
public function removeDocument(\AppBundle\Entity\Documents $document) {
$this->document->removeElement($document);
}
/**
* Get document
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDocument() {
return $this->document;
}
/**
* Add image
*
* #param \AppBundle\Entity\Images $image
* #return Products
*/
public function addImage(\AppBundle\Entity\Images $image) {
$this->image[] = $image;
return $this;
}
/**
* Remove image
*
* #param \AppBundle\Entity\Images $image
*/
public function removeImage(\AppBundle\Entity\Images $image) {
$this->image->removeElement($image);
}
/**
* Get image
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImage() {
return $this->image;
}
// CUSTOM CODE
/**
* Set providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
* #return Products
*/
/* public function setProviderRate(\AppBundle\Entity\ProviderRate $providerRate = null)
{
$this->providerRate = $providerRate;
return $this;
}
*/
/**
* Add providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
* #return Products
*/
public function addProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
$this->providerRate[] = $providerRate;
return $this;
}
/**
* Remove providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
*/
public function removeProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
$this->providerRate->removeElement($providerRate);
}
/**
* Get providerRate
*
* #return \AppBundle\Entity\ProviderRate
*/
public function getProviderRate()
{
return $this->providerRate;
}
}
ProviderRate Entity
/**
* ProviderRate
*
* #ORM\Table(name="provider_rate", indexes={#ORM\Index(name="fk_proveedor_has_producto_compra_producto_compra1_idx", columns={"product_id"}), #ORM\Index(name="fk_id_tarifa_proveedor_id_moneda1_idx", columns={"currency_id"}), #ORM\Index(name="IDX_3A645C45A53A8AA", columns={"provider_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProviderRateRepository")
*/
class ProviderRate
{
/**
* #var string
*
* #ORM\Column(name="reference", type="string", length=45, nullable=false)
*/
private $reference;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=true)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="unit_price", type="decimal", precision=25, scale=3, nullable=false)
*/
private $unitPrice;
/**
* #var string
*
* #ORM\Column(name="discount", type="decimal", precision=25, scale=3, nullable=false)
*/
private $discount;
/**
* #var \AppBundle\Entity\Providers
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Providers")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="provider_id", referencedColumnName="id")
* })
*/
private $provider;
/**
* #var \AppBundle\Entity\Products
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Products", inversedBy="providerRate")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
*
*/
private $product;
/**
* Set provider
*
* #param \AppBundle\Entity\Providers $provider
* #return ProviderRate
*/
public function setProvider(\AppBundle\Entity\Providers $provider)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return \AppBundle\Entity\Providers
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set product
*
* #param \AppBundle\Entity\Products $product
* #return ProviderRate
*/
public function setProduct(\AppBundle\Entity\Products $product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \AppBundle\Entity\Products
*/
public function getProduct()
{
return $this->product;
}
}
The code to run on the controller is as follows:
public function ajaxNewProductAction() {
$request = $this->getRequest();
$product = new Products();
$form = $this->createForm(new ProductsType(), $product);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
$em = $this->getDoctrine()->getManager();
$providerId = $request->get('provider');
$productVals = $request->get('Products');
$currency = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");
$product->setCurrency($currency);
$product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
$product->setIsactive(1);
$em->persist($product);
$em->flush();
$response['success'] = true;
$response['data'] = 0;
$response['providerId'] = $providerId;
}
else {
$response['success'] = false;
$response['cause'] = 'whatever';
}
return new JsonResponse($response);
}
return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
}
SOLVE:
I can solve it. The code of my entities thats ok. I change the controller function.
First I create the product object, set the providerRate to null and them persist it.
After I create the providerRate object and set the product object.
public function ajaxNewProductAction() {
$request = $this->getRequest();
$product = new Products();
$form = $this->createForm(new ProductsType(), $product);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
$em = $this->getDoctrine()->getManager();
$providerId = $request->get('provider');
$productVal = $request->get('Products');
$currency = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");
$product->setCurrency($currency);
$product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
$product->setProviderRate(null);
$em->persist($product);
$em->flush();
$providerRate = new ProviderRate();
$providerRate->setProvider($em->getRepository('AppBundle:Providers')->findOneById($providerId));
$providerRate->setProduct($product);
$providerRate->setReference($productVal["providerRate"][1]["reference"]);
$providerRate->setName($productVal["name"]);
$providerRate->setDescription($productVal["description"]);
$providerRate->setAmountPerUnit(1);
$providerRate->setUnitPrice(0);
$providerRate->setDiscount(0);
$providerRate->setCurrency($currency);
$providerRate->setProduct($product);
$em->persist($providerRate);
$em->flush();
$response['success'] = true;
}
else {
$response['success'] = false;
$response['cause'] = 'Algo ocurrió';
}
return new JsonResponse($response);
}
return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
}

Error trying flush an object in the database with Symfony2

I am new in Symfony2 (worked with Symfony 1 for several years) and I am trying to insert some records in a Entity with a relationship to another Entity, here are them:
<?php
namespace Jjj\SomeBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
/**
* Jjj\SomeBundle\Entity
*
* #ORM\Table(name="content")
* #ORM\Entity(repositoryClass="Jjj\SomeBundle\Entity\ContentRepository")
*/
class Content implements Translatable
{
/**
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="contents")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category_id;
/**
* #Gedmo\Translatable
* #ORM\Column(name="title", type="string", length=32, nullable=false)
*/
protected $title;
/**
* #Gedmo\Translatable
* #ORM\Column(name="summary", type="text", nullable=true)
*/
protected $summary;
/**
* #Gedmo\Translatable
* #ORM\Column(name="fulltext", type="text", nullable=true)
*/
protected $fulltext;
/**
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
*/
protected $created_at;
/**
*
* #ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
protected $updated_at;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(length=128, unique=true)
*/
private $slug;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set category_id
*
* #param integer $categoryId
* #return Content
*/
public function setCategoryId($categoryId)
{
$this->category_id = $categoryId;
return $this;
}
/**
* Get category_id
*
* #return integer
*/
public function getCategoryId()
{
return $this->category_id;
}
/**
* Set title
*
* #param string $title
* #return Content
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set slug
*
* #param string $slug
* #return Content
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set summary
*
* #param string $summary
* #return Content
*/
public function setSummary($summary)
{
$this->summary = $summary;
return $this;
}
/**
* Get summary
*
* #return string
*/
public function getSummary()
{
return $this->summary;
}
/**
* Set fulltext
*
* #param string $fulltext
* #return Content
*/
public function setFulltext($fulltext)
{
$this->fulltext = $fulltext;
return $this;
}
/**
* Get fulltext
*
* #return string
*/
public function getFulltext()
{
return $this->fulltext;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Content
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Content
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
}
This is the Category Entity:
<?php
namespace Jjj\SomeBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* Jjj\SomeBundle\Entity
*
* #ORM\Table(name="category")
* #ORM\Entity(repositoryClass="Jjj\SomeBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=32, nullable=false)
*/
protected $title;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
protected $created_at;
/**
* #var string
*
* #ORM\Column(name="updated_at", type="datetime", nullable=false)
*/
protected $updated_at;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(length=128, unique=true)
*/
private $slug;
/**
* #ORM\OneToMany(targetEntity="Content", mappedBy="category")
*/
protected $contents;
public function __construct()
{
$this->contents = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Category
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Category
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Category
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set slug
*
* #param string $slug
* #return Category
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Add contents
*
* #param \Jaguar\AloBundle\Entity\Content $contents
* #return Category
*/
public function addContent(\Jaguar\AloBundle\Entity\Content $contents)
{
$this->contents[] = $contents;
return $this;
}
/**
* Remove contents
*
* #param \Jjj\SomeBundle\Entity\Content $contents
*/
public function removeContent(\Jjj\SomeBundle\Entity\Content $contents)
{
$this->contents->removeElement($contents);
}
/**
* Get contents
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContents()
{
return $this->contents;
}
}
In the controller that is running, I wrote this:
$content = new Content();
$content->setTitle('Content Example');
$content->setSummary('Content Example');
$content->setFulltext('My first content...');
$content->setCategoryId(2);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($content);
$em->flush();
The error says:
ContextErrorException: Warning: spl_object_hash() expects parameter 1 to be object, integer given in D:\xampp\htdocs\projects\alopatria\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 1367
I was googling for a while but no luck found.
Any help, please?
Thanks!
You’re doing the mapping in Content.php in the wrong way.
If you’re setting a ManyToOne relation with the Category Entity, you should have a $category and not a $category_id attribute. You should deal with objects, and not integers.
Therefore, your Content Entity should look like this:
<?php
// Jjj\SomeBundle\Entity\Content.php
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="contents")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* Set category
*
* #param \Jjj\SomeBundle\Entity\Category $category
* #return Content
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return category
*/
public function getCategory()
{
return $this->category;
}
And your controller like this:
<?php
$category = new Category();
//… $category->setTitle() and so on…
$content = new Content();
$content->setTitle('Content Example');
$content->setSummary('Content Example');
$content->setFulltext('My first content...');
$content->setCategory($category);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($category);
$em->persist($content);
$em->flush();
You will then be able to access the id of a Category Entity (already fetched from database) with:
$categoryId = $category->getId();

Resources