I want to create a relation betwen 4 tables.
page (table for pages, fields: name, uri, status)
block (table for blocks, here i can have multipy records for specific page, fields: id, parrent_id, template)
block_content (table for contents of each block, here can have mulitpay records for a specific block, fields: id, block_id, lang, content)
block_relation (holding relations betwen page table and block table, fields: id, page_id, block_id)
How can i create relations betwen those tables.
Till now i've created this:
block_content:
<?php
namespace Casewise\Bundle\DispatcherBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BlockRelation
*
* #ORM\Table(name="block_relation")
* #ORM\Entity
*/
class BlockRelation
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Casewise\Bundle\PageBundle\Entity\Page", inversedBy="block_relation")
* #ORM\JoinColumn(name="page_id", referencedColumnName="page_id", nullable=FALSE)
*/
private $pageid;
/**
* #ORM\ManyToOne(targetEntity="Casewise\Bundle\CmsBundle\Entity\Block", inversedBy="block_relation")
* #ORM\JoinColumn(name="block_id", referencedColumnName="block_id", nullable=FALSE)
*/
private $blockid;
/** SETTERS AND GETTERS */
/**
* Gets the value of id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets the value of id.
*
* #param integer $id the id
*
* #return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Gets the value of pageid.
*
* #return integer
*/
public function getPageid()
{
return $this->pageid;
}
/**
* Sets the value of pageid.
*
* #param integer $pageid the pageid
*
* #return self
*/
public function setPageid($pageid)
{
$this->pageid = $pageid;
return $this;
}
/**
* Gets the value of blockid.
*
* #return integer
*/
public function getBlockid()
{
return $this->blockid;
}
/**
* Sets the value of blockid.
*
* #param integer $blockid the blockid
*
* #return self
*/
public function setBlockid($blockid)
{
$this->blockid = $blockid;
return $this;
}
}
block:
namespace Casewise\Bundle\CmsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
//use Doctrine\Common\Collections\ArrayCollection;
/**
* Block
*
* #ORM\Table(name="block")
* #ORM\Entity
*/
class Block
{
/**
* #var integer
*
* #ORM\Column(name="block_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $blockid;
/**
* #var integer
*
* #ORM\Column(name="parrent_id", type="integer")
*/
private $parrentid;
/**
* #var string
*
* #ORM\Column(name="template", type="string", length=150)
*/
private $template;
/**
* #var string
*
* #ORM\Column(name="status", type="boolean", options={"default" = 1})
*/
private $status;
/** SETTERS AND GETTERS */
/**
* Gets the value of blockid.
*
* #return integer
*/
public function getBlockid()
{
return $this->blockid;
}
/**
* Sets the value of blockid.
*
* #param integer $blockid the blockid
*
* #return self
*/
public function setBlockid($blockid)
{
$this->blockid = $blockid;
return $this;
}
/**
* Gets the value of parrentid.
*
* #return integer
*/
public function getParrentid()
{
return $this->parrentid;
}
/**
* Sets the value of parrentid.
*
* #param integer $parrentid the parrentid
*
* #return self
*/
public function setParrentid($parrentid)
{
$this->parrentid = $parrentid;
return $this;
}
/**
* Gets the value of template.
*
* #return string
*/
public function getTemplate()
{
return $this->template;
}
/**
* Sets the value of template.
*
* #param string $template the template
*
* #return self
*/
public function setTemplate($template)
{
$this->template = $template;
return $this;
}
/**
* Gets the value of status.
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Sets the value of status.
*
* #param string $status the status
*
* #return self
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
}
BlockContent:
<?php
namespace Casewise\Bundle\CmsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Block
*
* #ORM\Table(name="block_content")
* #ORM\Entity
*/
class BlockContent
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Casewise\Bundle\CmsBundle\Entity\Block", inversedBy="block_id")
* #ORM\JoinColumn(name="block_id", referencedColumnName="block_id", nullable=FALSE)
*/
private $blockid;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=150)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="language", type="string", length=15)
*/
private $language;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/** SETTERS AND GETTERS */
/**
* Gets the value of id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Sets the value of id.
*
* #param integer $id the id
*
* #return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Gets the value of blockid.
*
* #return integer
*/
public function getBlockid()
{
return $this->blockid;
}
/**
* Sets the value of blockid.
*
* #param integer $blockid the blockid
*
* #return self
*/
public function setBlockid($blockid)
{
$this->blockid = $blockid;
return $this;
}
/**
* Gets the value of name.
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the value of name.
*
* #param string $name the name
*
* #return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Gets the value of language.
*
* #return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* Sets the value of language.
*
* #param string $language the language
*
* #return self
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Gets the value of content.
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Sets the value of content.
*
* #param string $content the content
*
* #return self
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
}
Page
<?php
namespace Casewise\Bundle\PageBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
//use Doctrine\Common\Collections\ArrayCollection;
/**
* Page
*
* #ORM\Table(name="page")
* #ORM\Entity
*/
class Page
{
/**
* #var integer
*
* #ORM\Column(name="page_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $pageid;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="uri", type="string", length=255)
*/
private $uri;
/**
* #var string
*
* #ORM\Column(name="status", type="boolean", options={"default" = 1})
*/
private $status;
/** SETTERS AND GETTERS */
/**
* Gets the value of id.
*
* #return integer
*/
public function getPageId()
{
return $this->pageid;
}
/**
* Sets the value of id.
*
* #param integer $id the id
*
* #return self
*/
public function setPageId($pageid)
{
$this->pageid = $pageid;
return $this;
}
/**
* Gets the value of name.
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the value of name.
*
* #param string $name the name
*
* #return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Gets the value of uri.
*
* #return string
*/
public function getUri()
{
return $this->uri;
}
/**
* Sets the value of uri.
*
* #param string $uri the uri
*
* #return self
*/
public function setUri($uri)
{
$this->uri = $uri;
return $this;
}
/**
* Gets the value of status.
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Sets the value of status.
*
* #param string $status the status
*
* #return self
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
}
UPDATE:
I've update shema with: doctrine:schema:update --force
And when i request the Relation Entity and give him the pageid i need to get all related blocks to the specifc page, but it returns an huge object in which contains symfony2 specific objects(object with over 3000 lines), like requests, response and other objects which are not related to my request.
This is how i request entity:
$blocks = $this->getDoctrine()
->getRepository('CasewiseDispatcherBundle:BlockRelation')
->findByPageid(1);
echo '<pre>';
print_r($blocks);
echo '</pre>';
Related
I have a variable private $groupId; in entity. And there is a controller function public function settingsListAction(Request $request)
I want to access that groupId in controller function. How it can be achieved?
Edit
Controller function is
/**
* Get all settings content list
* #Route("settings", name="settings_list")
*/
public function settingsListAction(Request $request)
{
// Cannot edit at all.
//Fetch Current Financial Year target data to display that on "Road to paradise tab"
$entity = new J1Setting();
//do smthing
$groupIdValue = $entity->getGroup();
$settingsGroup = $this->getDoctrine()->getRepository('AppBundle:J1SettingGroup')->findAll();
$settingsList = $this->getDoctrine()->getRepository('AppBundle:J1Setting')->findBy(array('groupId' => groupIdValue));
return $this->render('default/settingsList.html.twig', array('settingsGroup' => $settingsGroup, 'settingsList' => $settingsList));
}
And entity is:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Component\Annotation\J1Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* J1Setting
*
* #ORM\Table(name="j1_settings", indexes={#ORM\Index(name="IDX_SName", columns={"name"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\J1SettingRepository")
* #J1Entity(auditClass="AppBundle\Component\Audit\J1AuditSetting")
*/
class J1Setting
{
/**
* #var integer
*
* #ORM\Column(name="setting_id", type="integer")
*
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $settingid;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="value", type="string", length=250, nullable=true)
*/
private $value;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="group_id", type="integer")
* #ORM\Id
*/
private $groupId;
/**
* #var J1SettingGroup
*
* #ORM\ManyToOne(targetEntity="J1SettingGroup", inversedBy="settings")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="group_id", referencedColumnName="id")
* })
*/
private $group;
/**
* #var string
*
* #ORM\Column(name="setting_type", type="string", length=100)
*/
private $settingType;
/**
* Get settingid
*
* #return integer
*/
public function getSettingId()
{
return $this->settingid;
}
/**
* Set name
*
* #param string $name
* #return J1Setting
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set value
*
* #param string $value
* #return J1Setting
*/
public function setValue($value)
{
$this->value = serialize($value);
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return unserialize($this->value);
}
/**
* Return name replacing underscores with spaces
*
* #return mixed
*/
public function getFriendlyName(){
return str_replace('_', ' ', $this->getName());
}
/**
* Set description
*
* #param string $description
* #return J1Setting
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set groupId
*
* #param integer $groupId
* #return J1Setting
*/
public function setGroupId($groupId)
{
$this->groupId = $groupId;
return $this;
}
/**
* Get groupId
*
* #return integer
*/
public function getGroupId()
{
return $this->groupId;
}
/**
* Set settingType
*
* #param string $settingType
* #return J1Setting
*/
public function setSettingType($settingType)
{
$this->settingType = $settingType;
return $this;
}
/**
* Get settingType
*
* #return string
*/
public function getSettingType()
{
return $this->settingType;
}
/**
* Set group
*
* #param $group
* #return J1Setting
*/
public function setGroup($group = null)
{
$this->group = $group;
return $this;
}
/**
* Get group
*
* #return integer
*/
public function getGroup()
{
return $this->group;
}
}
you need to create a getter in your entity
public function getGroupId(){
return $this->groupId;
}
public function setGroupId($groupId){
$this->groupId = $groupId;
}
and in your controller:
$entity = new J1Setting();
$entity->setGroupId(123);
$groupIdValue = $entity->getGroupId();
var_dump($goupIdValue) //outputs 123
When using Doctrine, you shouldn't put foreign keys into an entity.
This means, groupId should not be part of your J1Setting entity. If you want to access the id of the associated group, then you have to use $entity->getGroup()->getId(). Obviously, this only works, if the entity actually has a group!
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.
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
}
}
I have 3 tables: EdiTradingPartner, EdiDocType and EdiTradingPartnerTransactions
src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiTradingPartner
*
* #ORM\Table(name="edi_trading_partner")
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiTradingPartnerRepository")
*/
class EdiTradingPartner
{
/**
* #var string
*
* #ORM\Column(name="edi_interchange_id", type="string", length=30, nullable=false)
*/
private $ediInterchangeId;
/**
* #var string
*
* #ORM\Column(name="tp_name", type="string", length=30, nullable=false)
*/
private $tpName;
/**
* #var string
*
* #ORM\Column(name="tp_location", type="string", length=50, nullable=false)
*/
private $tpLocation;
/**
* #var integer
*
* #ORM\Column(name="edi_trading_partner_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediTradingPartnerId;
/**
* Set ediInterchangeId
*
* #param string $ediInterchangeId
* #return EdiTradingPartner
*/
public function setEdiInterchangeId($ediInterchangeId)
{
$this->ediInterchangeId = $ediInterchangeId;
return $this;
}
/**
* Get ediInterchangeId
*
* #return string
*/
public function getEdiInterchangeId()
{
return $this->ediInterchangeId;
}
/**
* Set tpName
*
* #param string $tpName
* #return EdiTradingPartner
*/
public function setTpName($tpName)
{
$this->tpName = $tpName;
return $this;
}
/**
* Get tpName
*
* #return string
*/
public function getTpName()
{
return $this->tpName;
}
/**
* Set tpLocation
*
* #param string $tpLocation
* #return EdiTradingPartner
*/
public function setTpLocation($tpLocation)
{
$this->tpLocation = $tpLocation;
return $this;
}
/**
* Get tpLocation
*
* #return string
*/
public function getTpLocation()
{
return $this->tpLocation;
}
/**
* Get ediTradingPartnerId
*
* #return integer
*/
public function getEdiTradingPartnerId()
{
return $this->ediTradingPartnerId;
}
}
src\Matrix\MatrixEdiBundle\Entity\EdiDocType
<?php
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiDocType
*
* #ORM\Table(name="edi_doc_type")
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiDocTypeRepository")
*/
class EdiDocType
{
/**
* #var integer
*
* #ORM\Column(name="doc_type", type="integer", nullable=false)
*/
private $docType;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="direction", type="string", length=10, nullable=false)
*/
private $direction;
/**
* #var integer
*
* #ORM\Column(name="edi_doc_type_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediDocTypeId;
/**
* Set docType
*
* #param integer $docType
* #return EdiDocType
*/
public function setDocType($docType)
{
$this->docType = $docType;
return $this;
}
/**
* Get docType
*
* #return integer
*/
public function getDocType()
{
return $this->docType;
}
/**
* Set name
*
* #param string $name
* #return EdiDocType
*/
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 EdiDocType
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set direction
*
* #param string $direction
* #return EdiDocType
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Get direction
*
* #return string
*/
public function getDirection()
{
return $this->direction;
}
/**
* Get ediDocTypeId
*
* #return integer
*/
public function getEdiDocTypeId()
{
return $this->ediDocTypeId;
}
}
src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions
namespace Matrix\MatrixEdiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* EdiTradingPartnerTransactions
*
* #ORM\Table(name="edi_trading_partner_transactions", indexes={#ORM\Index(name="edi_tp_id", columns={"edi_tp_id", "edi_doc_type_id"}), #ORM\Index(name="edi_transactions_id", columns={"edi_doc_type_id"}), #ORM\Index(name="IDX_F2BE50F7B9C737A1", columns={"edi_tp_id"})})
* #ORM\Entity(repositoryClass="Matrix\MatrixEdiBundle\Repository\EdiTradingPartnerTransactionsRepository")
*/
class EdiTradingPartnerTransactions
{
/**
* #var integer
*
* #ORM\Column(name="edi_tp_transactions_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $ediTpTransactionsId;
/**
* #var \Matrix\MatrixEdiBundle\Entity\EdiDocType
*
* #ORM\ManyToOne(targetEntity="Matrix\MatrixEdiBundle\Entity\EdiDocType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="edi_doc_type_id", referencedColumnName="edi_doc_type_id")
* })
*/
private $ediDocType;
/**
* #var \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
*
* #ORM\ManyToOne(targetEntity="Matrix\MatrixEdiBundle\Entity\EdiTradingPartner")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="edi_tp_id", referencedColumnName="edi_trading_partner_id")
* })
*/
private $ediTp;
/**
* Get ediTpTransactionsId
*
* #return integer
*/
public function getEdiTpTransactionsId()
{
return $this->ediTpTransactionsId;
}
/**
* Set ediDocType
*
* #param \Matrix\MatrixEdiBundle\Entity\EdiDocType $ediDocType
* #return EdiTradingPartnerTransactions
*/
public function setEdiDocType(\Matrix\MatrixEdiBundle\Entity\EdiDocType $ediDocType = null)
{
$this->ediDocType = $ediDocType;
return $this;
}
/**
* Get ediDocType
*
* #return \Matrix\MatrixEdiBundle\Entity\EdiDocType
*/
public function getEdiDocType()
{
return $this->ediDocType;
}
/**
* Set ediTp
*
* #param \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner $ediTp
* #return EdiTradingPartnerTransactions
*/
public function setEdiTp(\Matrix\MatrixEdiBundle\Entity\EdiTradingPartner $ediTp = null)
{
$this->ediTp = $ediTp;
return $this;
}
/**
* Get ediTp
*
* #return \Matrix\MatrixEdiBundle\Entity\EdiTradingPartner
*/
public function getEdiTp()
{
return $this->ediTp;
}
}
I want to insert into EdiTradingPartnerTransactions table yet I really don't know what to do since I've been receiving this error:
Catchable fatal error: Argument 1 passed to
Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions::setEdiTp()
must be an instance of
Matrix\MatrixEdiBundle\Entity\EdiTradingPartner, string given, called
in
C:\xampp\htdocs\Editracker\src\Matrix\MatrixEdiBundle\Controller\MatrixController.php
on line 474 and defined in
C:\xampp\htdocs\Editracker\src\Matrix\MatrixEdiBundle\Entity\EdiTradingPartnerTransactions.php
on line 85
Here's my function in the controller side:
public function deleteTpTransAction($tpId, $docType, $direction, $tpName) {
$em = $this->getDoctrine()->getManager();
$docTypeId = $em->getRepository('MatrixEdiBundle:EdiDocType')->getId($docType, $direction);
if ($docTypeId != null) {
$result = $em->getRepository('MatrixEdiBundle:EdiTradingPartnerTransactions')->getTpTrans($tpId, $docType, $direction);
if ($result == null) {
$transaction = new EdiTradingPartnerTransactions();
$transaction->setEdiTp($tpId);
$transaction->setEdiDocType($docTypeId);
$em->persist($transaction);
} else {
foreach ($result as $key) {
$id = $key->getEdiTpTransactionsId();
$transaction = $em->getRepository('MatrixEdiBundle:EdiTradingPartnerTransactions')->find($id);
$em->remove($transaction);
}
}
$em->flush();
}
return $this->redirect($this->generateUrl('matrix_edi_tpTrans'));
}
Any help would really be appreciated. Thanks in advanced!
The error here is pretty clear: Doctrine handle, at least for relationships, only objects of the "related" (let's call that way) entity.
When you do
$transaction->setEdiTp($tpId);
$transaction->setEdiDocType($docTypeId);
you're trying to insert ID(s) of related objects. This is an error: although your db expects an integer (foreign key), Doctrine is an abstaction "pillow" between your code and db; it choose to work with objects and not with ids(you can see it pretty clearly into entity classes files)
Solution here is pretty simple:
Fetch from db the entity for setEdiTp and setEdiDocType
Pass them to the functions
In PHP (Symfony):
$ediTp = $em
->getRepository('MatrixEdiBundle:EdiTp')
->findOneById($tpId);
$ediDocType = $em
->getRepository('MatrixEdiBundle:EdiDocType')
->findOneById($docTypeId);
then
$transaction->setEdiTp($ediTp);
$transaction->setEdiDocType($ediDocType);
Your error is because setEdiTp need an instance of EdiTradingPartner.
Your error say string given.
Because $tpId is string.
Verify
Change
$transaction->setEdiTp($tpId);
To
// $transaction->setEdiTp($tpId);
var_dump($tpId);
Normally, $tpId return a string, not a object.
So when you call deleteTpTransAction, $tpId must be an instance of setEdiTp
Changement :
$editp = $em->getRepository('MatrixEdiBundle:EdiTradingPartner')->find($tpId);
and change
$transaction->setEdiTp($tpId);
by
$transaction->setEdiTp($editTp);
I'm trying to add a simple comment entity, with the "postedOn" attribute as a Datetime. Whenever I try to add a comment, I get this error :
Error: Call to undefined method Symfony\Component\Validator\Constraints\DateTime::format() in /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php line 53
Any idea ?
Here's the entity code :
<?php
namespace AOFVH\FlyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Comment
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AOFVH\FlyBundle\Entity\CommentRepository")
*/
class Comment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="rating", type="integer")
*/
private $rating;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $postedon;
/**
* #var string
*
* #ORM\Column(name="text", type="text")
*/
private $text;
/**
* #var $commenter
*
* #ORM\ManyToOne(targetEntity="AOFVH\UserBundle\Entity\User", inversedBy="comments", cascade={"persist", "merge"})
*/
private $commenter;
/**
* #var $commenter
*
* #ORM\ManyToOne(targetEntity="AOFVH\FlyBundle\Entity\Flight", inversedBy="comments", cascade={"persist", "merge"})
*/
private $flight;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set rating
*
* #param integer $rating
* #return Comment
*/
public function setRating($rating)
{
$this->rating = $rating;
return $this;
}
/**
* Get rating
*
* #return integer
*/
public function getRating()
{
return $this->rating;
}
/**
* Set text
*
* #param string $text
* #return Comment
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set commenter
*
* #param \AOFVH\UserBundle\Entity\User $commenter
* #return Comment
*/
public function setCommenter(\AOFVH\UserBundle\Entity\User $commenter = null)
{
$this->commenter = $commenter;
return $this;
}
/**
* Get commenter
*
* #return \AOFVH\UserBundle\Entity\User
*/
public function getCommenter()
{
return $this->commenter;
}
/**
* Set flight
*
* #param \AOFVH\FlyBundle\Entity\Flight $flight
* #return Comment
*/
public function setFlight(\AOFVH\FlyBundle\Entity\Flight $flight = null)
{
$this->flight = $flight;
return $this;
}
/**
* Get flight
*
* #return \AOFVH\FlyBundle\Entity\Flight
*/
public function getFlight()
{
return $this->flight;
}
Here are the postedOn getters and setters
/**
* Set postedon
*
* #param \DateTime $postedon
* #return Comment
*/
public function setPostedon($postedon)
{
$this->postedon = $postedon;
return $this;
}
/**
* Get postedon
*
* #return \DateTime
*/
public function getPostedon()
{
return $this->postedon;
}
}
I think it's your mapping in your entity, you don't use "datetime" doctrine format else your form type will try to generate a date with a string for example but for me "postedOn must always be defined on a new comment.You can update your entity constructor with : $this->setPostedOn(new \Datetime()); or you can use TimestampableTrait