I have entity named Sections, who have:
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="sections")
*/
protected $products;
And entity named Product, who have:
/**
* #ORM\OneToMany(targetEntity="Price", mappedBy="product")
*/
protected $price;
Now I use:
$sectionsarray = $this->getDoctrine()
->getRepository('AsortBundle:Sections')
->createQueryBuilder('e')
->leftJoin('e.products', 'p')
->leftJoin('e.colors', 'c')
->select('e, p, c')
->orderBy('e.sequence', 'asc')
->addOrderBy('p.kolejnosc', 'asc')
->addOrderBy('c.sequence', 'asc')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
How I can join price of these product? Price is array collection because it have four currencies.
Entity/Product.php
/**
* #ORM\ManyToOne(targetEntity="Price", inversedBy="products")
* #ORM\JoinColumn(name="price_id", referencedColumnName="id")
*/
private $price;
Entity/Price.php
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="price")
*/
private $products;
Repository/SectionsRpository.php
$sectionsarray = $this->getDoctrine()
->getRepository('AsortBundle:Sections')
->createQueryBuilder('e')
->leftJoin('e.products', 'p')
**->leftJoin('p.price', 'pr')**
->leftJoin('e.colors', 'c')
->select('e, p, c, pr')
->orderBy('e.sequence', 'asc')
->addOrderBy('p.kolejnosc', 'asc')
->addOrderBy('c.sequence', 'asc')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
You need to add another join:
$sectionsarray = $this->getDoctrine()
->getRepository('AsortBundle:Sections')
->createQueryBuilder('e')
->select('e, p, c, prices')
->leftJoin('e.products', 'p')
->leftJoin('p.prices', 'prices')
->leftJoin('e.colors', 'c')
->orderBy('e.sequence', 'asc')
->addOrderBy('p.kolejnosc', 'asc')
->addOrderBy('c.sequence', 'asc')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
I used prices instead of price, because field representing one to many should be in plural form.
probably not quite what I meant
My Product Entity:
<?
namespace AsortBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="asortyment")
*/
class Product implements Translatable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Gedmo\Translatable
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $name;
/**
* #Gedmo\Translatable
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $img;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $rozmiar;
/**
* #ORM\Column(type="integer")
*/
protected $dostepnosc = 1;
/**
* #ORM\Column(type="integer")
*/
protected $kolejnosc;
/**
* #ORM\Column(type="bigint", length=13)
*/
protected $kodog;
/**
* #ORM\Column(type="bigint", length=13)
*/
protected $kodsz;
/**
* #ORM\Column(type="bigint", length=13, nullable=true)
*/
protected $parent;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $min;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $opt;
/**
* #ORM\OneToMany(targetEntity="Price", mappedBy="product")
*/
protected $price;
/**
* #Gedmo\Translatable
* #ORM\Column(type="text", nullable=true)
*/
protected $description;
/**
* #Gedmo\Locale
* Used locale to override Translation listener`s locale
* this is not a mapped field of entity metadata, just a simple property
*/
private $locale;
/**
* #ORM\ManyToOne(targetEntity="Sections", inversedBy="products")
* #ORM\JoinColumn(name="section_id", referencedColumnName="id")
*/
protected $sections;
/**
* #ORM\ManyToOne(targetEntity="Sections", inversedBy="lazyproducts")
* #ORM\JoinColumn(name="section_id", referencedColumnName="id")
*/
//protected $sections2;
/**
* #ORM\ManyToOne(targetEntity="Colors")
* #ORM\JoinColumn(name="color_id", referencedColumnName="id")
*/
protected $color;
/**
* #ORM\OneToOne(targetEntity="Magazyn")
* #ORM\JoinColumn(name="magazyn_id", referencedColumnName="id", nullable=true)
**/
private $magazyn;
public function __construct() {
$this->price = new ArrayCollection();
}
/**
* 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 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;
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
/**
* Set img
*
* #param string $img
* #return Product
*/
public function setImg($img)
{
$this->img = $img;
return $this;
}
/**
* Get img
*
* #return string
*/
public function getImg()
{
return $this->img;
}
/**
* Set rozmiar
*
* #param string $rozmiar
* #return Product
*/
public function setRozmiar($rozmiar)
{
$this->rozmiar = $rozmiar;
return $this;
}
/**
* Get rozmiar
*
* #return string
*/
public function getRozmiar()
{
return $this->rozmiar;
}
/**
* Set dostepnosc
*
* #param integer $dostepnosc
* #return Product
*/
public function setDostepnosc($dostepnosc)
{
$this->dostepnosc = $dostepnosc;
return $this;
}
/**
* Get dostepnosc
*
* #return integer
*/
public function getDostepnosc()
{
return $this->dostepnosc;
}
/**
* Set kolejnosc
*
* #param integer $kolejnosc
* #return Product
*/
public function setKolejnosc($kolejnosc)
{
$this->kolejnosc = $kolejnosc;
return $this;
}
/**
* Get kolejnosc
*
* #return integer
*/
public function getKolejnosc()
{
return $this->kolejnosc;
}
/**
* Set kodog
*
* #param integer $kodog
* #return Product
*/
public function setKodog($kodog)
{
$this->kodog = $kodog;
return $this;
}
/**
* Get kodog
*
* #return integer
*/
public function getKodog()
{
return $this->kodog;
}
/**
* Set kodsz
*
* #param integer $kodsz
* #return Product
*/
public function setKodsz($kodsz)
{
$this->kodsz = $kodsz;
return $this;
}
/**
* Get kodsz
*
* #return integer
*/
public function getKodsz()
{
return $this->kodsz;
}
/**
* Set parent
*
* #param integer $parent
* #return Product
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return integer
*/
public function getParent()
{
return $this->parent;
}
/**
* Set min
*
* #param integer $min
* #return Product
*/
public function setMin($min)
{
$this->min = $min;
return $this;
}
/**
* Get min
*
* #return integer
*/
public function getMin()
{
return $this->min;
}
/**
* Set opt
*
* #param integer $opt
* #return Product
*/
public function setOpt($opt)
{
$this->opt = $opt;
return $this;
}
/**
* Get opt
*
* #return integer
*/
public function getOpt()
{
return $this->opt;
}
/**
* Set sections
*
* #param \AsortBundle\Entity\Sections $sections
* #return Product
*/
public function setSections(\AsortBundle\Entity\Sections $sections = null)
{
$this->sections = $sections;
return $this;
}
/**
* Get sections
*
* #return \AsortBundle\Entity\Sections
*/
public function getSections()
{
return $this->sections;
}
/**
* Set magazyn
*
* #param \AsortBundle\Entity\Magazyn $magazyn
* #return Product
*/
public function setMagazyn(\AsortBundle\Entity\Magazyn $magazyn = null)
{
$this->magazyn = $magazyn;
return $this;
}
/**
* Get magazyn
*
* #return \AsortBundle\Entity\Magazyn
*/
public function getMagazyn()
{
return $this->magazyn;
}
/**
* Set color
*
* #param \AsortBundle\Entity\Colors $color
* #return Product
*/
public function setColor(\AsortBundle\Entity\Colors $color = null)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return \AsortBundle\Entity\Colors
*/
public function getColor()
{
return $this->color;
}
/**
* Add price
*
* #param \AsortBundle\Entity\Price $price
* #return Product
*/
public function addPrice(\AsortBundle\Entity\Price $price)
{
$this->price[] = $price;
return $this;
}
/**
* Remove price
*
* #param \AsortBundle\Entity\Price $price
*/
public function removePrice(\AsortBundle\Entity\Price $price)
{
$this->price->removeElement($price);
}
/**
* Get price
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPrice()
{
return $this->price;
}
}
My Price Entity:
<?
namespace AsortBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="price")
*/
class Price
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Currency")
* #ORM\JoinColumn(name="currency_id", referencedColumnName="id")
*/
private $currency;
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="price")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
/**
* #ORM\Column(type="decimal", nullable=true, precision=10, scale=2)
*/
protected $val;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set val
*
* #param string $val
* #return Price
*/
public function setVal($val)
{
$this->val = $val;
return $this;
}
/**
* Get val
*
* #return string
*/
public function getVal()
{
return $this->val;
}
/**
* Set currency
*
* #param \AsortBundle\Entity\Currency $currency
* #return Price
*/
public function setCurrency(\AsortBundle\Entity\Currency $currency = null)
{
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return \AsortBundle\Entity\Currency
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set product
*
* #param \AsortBundle\Entity\Product $product
* #return Price
*/
public function setProduct(\AsortBundle\Entity\Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \AsortBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
}
My Currency Entity:
<?
namespace AsortBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Translatable;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="currency")
*/
class Currency implements Translatable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Gedmo\Translatable
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
protected $iso;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Currency
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set iso
*
* #param string $iso
* #return Currency
*/
public function setIso($iso)
{
$this->iso = $iso;
return $this;
}
/**
* Get iso
*
* #return string
*/
public function getIso()
{
return $this->iso;
}
}
In session I got current cyrrency in ISO format like PLN, USD, EUR, RUB.
Now I want get from product his actually price in currency which I keep in session, like PLN.
ok I wrote custom getters and for now work nice :)
in Price Entity:
/**
* Get val
*
* #return string
*/
public function getValWithCurrency()
{
return array($this->currency->getIso() => $this->val);
}
in Product Entity:
/**
* Get val
*
* #return string
*/
public function getPriceArray()
{
$arr = array();
$pra = $this->price->toArray();
foreach($pra as $k => $v){
$a = $v->getValWithCurrency();
$arr = array_merge($arr, $a);
}
return $arr;
}
enter image description here
I can now add getter with currency from session or use currency session like a key.
And for get all:
$c = $this->get('session')->get('currency');
$sectionsarray = $this->getDoctrine()
->getRepository('AsortBundle:Sections')
->createQueryBuilder('e')
->select('e, p, c, prices, cur')
->leftJoin('e.products', 'p')
->leftJoin('p.price', 'prices')
->leftJoin('e.colors', 'c')
->leftJoin('prices.currency', 'cur')
->where('cur.iso = :sesscurr')
->setParameter('sesscurr', 'PLN')
->orderBy('e.sequence', 'asc')
->addOrderBy('p.kolejnosc', 'asc')
->addOrderBy('c.sequence', 'asc')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
Thanks!
Related
I need to find a single row from the database and I am using findOneBy().
findBy() and findOneBy() and any other symfony functions always return an empty array collection for my ManyToOne related entities when I loop through the collection.
But when using findAll() function and I loop through the collection, it returns the expected data.
You will find the controller function at the end of the question with the different find functions I have used and do not work.
Entities listed below:
The news entity is related to the newsBlocks entity and newsBlocks is related to the legalNotices entity.
They all are related by ManyToOne/OneToMany relationship.
News Entity
<?php
namespace Honda\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* News
*
* #ORM\Table(name="news")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\NewsRepository")
*/
class News
{
use Traits\DistributorTrait,
Traits\StartDateEndDateTrait,
Traits\HomeActivationTrait,
Traits\ActivationTrait,
Traits\RedirectionTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\NotBlank()
* #ORM\Column(name="title", type="string", length=255, nullable=true)
*/
private $title;
/**
* #var string
*
* #Assert\NotBlank()
* #ORM\Column(name="description1", type="text", nullable=true)
*/
private $description1;
/**
* #var integer
*
* #ORM\Column(name="type", type="integer", nullable=true)
*/
private $type;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(unique=true)
*/
private $slug;
/**
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"all"}, fetch="LAZY")
* #ORM\JoinColumn(name="image", referencedColumnName="id", onDelete="SET NULL", nullable=true)
*/
protected $image;
/**
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"all"}, fetch="LAZY")
* #ORM\JoinColumn(name="image_mobile", referencedColumnName="id", onDelete="SET NULL", nullable=true)
*/
protected $image_mobile;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
*/
protected $createdAt;
/**
* #Gedmo\SortablePosition
* #ORM\Column(name="position", type="integer")
*/
private $position;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\NewsBlocks", mappedBy="news", cascade={"persist"})
*/
private $newsBlocks;
/**
* Constructor.
*/
public function __construct()
{
$this->createdAt = new \DateTime('NOW', new \DateTimeZone('Europe/Paris'));
$this->slides = new ArrayCollection();
$this->newsBlocks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return string
*/
public function __toString()
{
if ($this->getId()) {
return $this->getTitle();
}
return '';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return News
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description1
*
* #param string $description1
*
* #return News
*/
public function setDescription1($description1)
{
$this->description1 = $description1;
return $this;
}
/**
* Get description1
*
* #return string
*/
public function getDescription1()
{
return $this->description1;
}
/**
* Set type
*
* #param integer $type
*
* #return News
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType()
{
return $this->type;
}
/**
* Set image
*
* #param \Application\Sonata\MediaBundle\Entity\Media $image
*
* #return News
*/
public function setImage(\Application\Sonata\MediaBundle\Entity\Media $image = null)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return \Application\Sonata\MediaBundle\Entity\Media
*/
public function getImage()
{
return $this->image;
}
/**
* Set slug
*
* #param string $slug
*
* #return News
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return News
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set position
*
* #param integer $position
*
* #return ALaUne
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* #return integer
*/
public function getPosition()
{
return $this->position;
}
/**
* Set imageMobile.
*
* #param \Application\Sonata\MediaBundle\Entity\Media|null $imageMobile
*
* #return News
*/
public function setImageMobile(\Application\Sonata\MediaBundle\Entity\Media $imageMobile = null)
{
$this->image_mobile = $imageMobile;
return $this;
}
/**
* Get imageMobile.
*
* #return \Application\Sonata\MediaBundle\Entity\Media|null
*/
public function getImageMobile()
{
return $this->image_mobile;
}
/**
* Add newsBlock.
*
* #param \Honda\MainBundle\Entity\NewsBlocks $newsBlock
*
* #return NewNews
*/
public function addNewsBlock(\Honda\MainBundle\Entity\NewsBlocks $newsBlock)
{
if (!$this->newsBlocks->contains($newsBlock)) {
$this->newsBlocks[] = $newsBlock;
$newsBlock->setNews($this);
}
return $this;
}
/**
* Remove newsBlock.
*
* #param \Honda\MainBundle\Entity\NewsBlocks $newsBlock
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeNewsBlock(\Honda\MainBundle\Entity\NewsBlocks $newsBlock)
{
if (!$this->newsBlocks->contains($newsBlock)) {
return;
}
$this->newsBlocks->removeElement($newsBlock);
$newsBlock->setNews(null);
return $this;
}
/**
* Get newsBlocks.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNewsBlocks()
{
return $this->newsBlocks;
}
}
NewsBlocks
<?php
namespace Honda\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Honda\MainBundle\Entity\Traits;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* NewsBlocks
*
* #ORM\Table(name="news_blocks")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\NewsBlocksRepository")
*/
class NewsBlocks
{
use Traits\DistributorTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="block_name", type="string", length=255)
*/
private $blockName;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\Offer", mappedBy="newsBlockOffer", cascade={"all"})
*/
private $offers;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\Video", mappedBy="newsBlockVideo", cascade={"persist"})
*/
private $videos;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\LegalNotices", mappedBy="newsBlockLegalNotices", cascade={"persist"})
*/
private $legalNotices;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\OfferCarousel", mappedBy="newsOfferBlocks", cascade={"persist"})
*/
private $offerCarousels;
/**
* #ORM\ManyToOne(targetEntity="Honda\MainBundle\Entity\News", inversedBy="newsBlocks", cascade={"persist"})
*/
private $news;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\PhotoSlider", mappedBy="newsPhotoSliderBlock", cascade={"persist"})
*/
private $photoSliders;
/**
* #ORM\Column(name="position", type="integer")
*/
private $position;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Constructor
*/
public function __construct()
{
$this->offers = new \Doctrine\Common\Collections\ArrayCollection();
$this->videos = new \Doctrine\Common\Collections\ArrayCollection();
$this->legalNotices = new \Doctrine\Common\Collections\ArrayCollection();
$this->offerCarousels = new \Doctrine\Common\Collections\ArrayCollection();
$this->photoSliders = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add offer.
*
* #param \Honda\MainBundle\Entity\News\Offer $offer
*
* #return NewsBlocks
*/
public function addOffer(\Honda\MainBundle\Entity\News\Offer $offer)
{
if (!$this->offers->contains($offer)) {
$this->offers[] = $offer;
$offer->setNewsBlockOffer($this);
}
return $this;
}
/**
* Remove offer.
*
* #param \Honda\MainBundle\Entity\News\Offer $offer
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeOffer(\Honda\MainBundle\Entity\News\Offer $offer)
{
if (!$this->offers->contains($offer)) {
return;
}
$this->offers->removeElement($offer);
$offer->setNewsBlockOffers(null);
return $this;
}
/**
* Get offers.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getOffers()
{
return $this->offers;
}
/**
* Add video.
*
* #param \Honda\MainBundle\Entity\News\Video $video
*
* #return NewsBlocks
*/
public function addVideo(\Honda\MainBundle\Entity\News\Video $video)
{
if (!$this->videos->contains($video)) {
$this->videos[] = $video;
$video->setNewsBlockVideo($this);
}
return $this;
}
/**
* Remove video.
*
* #param \Honda\MainBundle\Entity\News\Video $video
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeVideo(\Honda\MainBundle\Entity\News\Video $video)
{
if (!$this->videos->contains($video)) {
return;
}
$this->videos->removeElement($video);
$video->setNewsBlockVideo(null);
return $this;
}
/**
* Get videos.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVideos()
{
return $this->videos;
}
/**
* Set blockName.
*
* #param string $blockName
*
* #return NewsBlocks
*/
public function setBlockName($blockName)
{
$this->blockName = $blockName;
return $this;
}
/**
* Get blockName.
*
* #return string
*/
public function getBlockName()
{
return $this->blockName;
}
/**
* Add legalNotice.
*
* #param \Honda\MainBundle\Entity\News\LegalNotices $legalNotice
*
* #return NewsBlocks
*/
public function addLegalNotice(\Honda\MainBundle\Entity\News\LegalNotices $legalNotice)
{
if (!$this->legalNotices->contains($legalNotice)) {
$this->legalNotices[] = $legalNotice;
$legalNotice->setNewsBlockLegalNotices($this);
}
return $this;
}
/**
* Remove legalNotice.
*
* #param \Honda\MainBundle\Entity\News\LegalNotices $legalNotice
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeLegalNotice(\Honda\MainBundle\Entity\News\LegalNotices $legalNotice)
{
if (!$this->legalNotices->contains($legalNotice)) {
return;
}
$this->legalNotices->removeElement($legalNotice);
$legalNotice->setUniqueLook(null);
return $this;
}
/**
* Get legalNotices.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLegalNotices()
{
return $this->legalNotices;
}
/**
* Add offerCarousel.
*
* #param \Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel
*
* #return NewsBlocks
*/
public function addOfferCarousel(\Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel)
{
if (!$this->offerCarousels->contains($offerCarousel)) {
$this->offerCarousels[] = $offerCarousel;
$offerCarousel->setNewsOfferBlocks($this);
}
return $this;
}
/**
* Remove offerCarousel.
*
* #param \Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeOfferCarousel(\Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel)
{
if (!$this->offerCarousels->contains($offerCarousel)) {
return;
}
$this->offerCarousels->removeElement($offerCarousel);
$offerCarousel->setNewsOfferBlocks(null);
return $this;
}
/**
* Get offerCarousels.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getOfferCarousels()
{
return $this->offerCarousels;
}
/**
* Set news.
*
* #param \Honda\MainBundle\Entity\News|null $news
*
* #return NewsBlocks
*/
public function setNews(\Honda\MainBundle\Entity\News $news = null)
{
$this->news = $news;
return $this;
}
/**
* Get news.
*
* #return \Honda\MainBundle\Entity\News|null
*/
public function getNews()
{
return $this->news;
}
/**
* Add photoSlider.
*
* #param \Honda\MainBundle\Entity\News\PhotoSlider $photoSlider
*
* #return NewsBlocks
*/
public function addPhotoSlider(\Honda\MainBundle\Entity\News\PhotoSlider $photoSlider)
{
if (!$this->photoSliders->contains($photoSlider)) {
$this->photoSliders[] = $photoSlider;
$photoSlider->setNewsPhotoSliderBlock($this);
}
return $this;
}
/**
* Remove photoSlider.
*
* #param \Honda\MainBundle\Entity\News\PhotoSlider $photoSlider
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removePhotoSlider(\Honda\MainBundle\Entity\News\PhotoSlider $photoSlider)
{
if (!$this->photoSliders->contains($photoSlider)) {
return;
}
$this->photoSliders->removeElement($photoSlider);
$photoSlider->setNewsPhotoSliderBlock(null);
}
/**
* Get slides.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPhotoSliders()
{
return $this->photoSliders;
}
/**
* Set position.
*
* #param int $position
*
* #return NewsBlocks
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position.
*
* #return int
*/
public function getPosition()
{
return $this->position;
}
}
Legal Notices
<?php
namespace Honda\MainBundle\Entity\News;
use Doctrine\ORM\Mapping as ORM;
use Honda\MainBundle\Entity\Traits;
/**
* LegalNotices
*
* #ORM\Table(name="news_legal_notices")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\News\LegalNoticesRepository")
*/
class LegalNotices
{
use Traits\DistributorTrait,
Traits\ActivationTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Honda\MainBundle\Entity\NewsBlocks", inversedBy="legalNotices", cascade={"persist"})
*/
private $newsBlockLegalNotices;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set description.
*
* #param string $description
*
* #return LegalNotices
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description.
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set newsBlockLegalNotices.
*
* #param \Honda\MainBundle\Entity\NewsBlocks|null $newsBlockLegalNotices
*
* #return LegalNotices
*/
public function setNewsBlockLegalNotices(\Honda\MainBundle\Entity\NewsBlocks $newsBlockLegalNotices = null)
{
$this->newsBlockLegalNotices = $newsBlockLegalNotices;
return $this;
}
/**
* Get newsBlockLegalNotices.
*
* #return \Honda\MainBundle\Entity\NewsBlocks|null
*/
public function getNewsBlockLegalNotices()
{
return $this->newsBlockLegalNotices;
}
}
Here is my function in the controller:
/**
* #Route("/actualites/{slug}", name="news_show_article", requirements={"slug": "[a-zA-Z0-9\-]+"})
*/
public function articleAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$news = $em->getRepository(News::class)->findBy(['slug' => $slug]); // Return specific row but collection emtpy
$news = $em->getRepository(News::class)->findOneBy(['slug' => $slug]); // Return specific row but collection emtpy
$news = $em->getRepository(News::class)->findBy([], ['createdAt' => 'DESC']); // Return all but collection empty
$r = $news[16]->getNewsBlocks();
foreach ($r as $item) {
dump($item);
}
$news = $em->getRepository(News::class)->findAll(); // Return all and collection is not emtpy
$r = $news[16]->getNewsBlocks();
foreach ($r as $item) {
foreach($item->getOffers() as $offer) {
dump($offer);
}
}
}
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 these 3 entities below. Keep in mind that Pedido is like Order/Cart, and Subitem is like Product.
Pedido:
namespace Project\FrontendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
//use Gedmo\Mapping\Annotation as Gedmo;
/**
* Project\FrontendBundle\Entity\Pedido
*
* #ORM\Table
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Pedido
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="pedidos")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
**/
private $user;
/**
* #ORM\OneToMany(targetEntity="PedidoSubitem", mappedBy="pedido", cascade={"persist", "remove"})
**/
private $pedidoSubitems;
/**
* #ORM\Column(type="float", name="subtotal")
*/
private $subtotal;
/**
* #ORM\Column(type="float", name="iva")
*/
private $iva;
/**
* #ORM\Column(type="float", name="total")
*/
private $total;
/**
* #ORM\Column(type="text", length=5000, name="notas", nullable=true)
*
* #var text $notas
*/
private $notas;
/**
* #var \DateTime $created
*
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $updated;
/**
* #var \DateTime $contentChanged
*
* #ORM\Column(name="content_changed", type="datetime", nullable=true)
*/
private $contentChanged;
public function __construct() {
$this->pedidoSubitems = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set cliente
*
* #param \Project\FrontendBundle\Entity\Cliente $cliente
* #return Pedido
*/
public function setCliente(\Project\FrontendBundle\Entity\Cliente $cliente = null)
{
$this->cliente = $cliente;
return $this;
}
/**
* Get cliente
*
* #return \Project\FrontendBundle\Entity\Cliente
*/
public function getCliente()
{
return $this->cliente;
}
/**
* Add pedidoSubitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems
* #return Pedido
*/
public function addPedidoSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems)
{
$this->pedidoSubitems[] = $pedidoSubitems;
return $this;
}
public function addPedido(\Project\FrontendBundle\Entity\Pedido $pedido)
{
$this->pedidoSubitems[] = $pedido;
}
/**
* Remove pedidoSubitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems
*/
public function removePedidoSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems)
{
$this->pedidoSubitems->removeElement($pedidoSubitems);
}
/**
* Get pedidoSubitems
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPedidoSubitems()
{
return $this->pedidoSubitems;
}
/**
* Set user
*
* #param \Project\FrontendBundle\Entity\User $user
* #return Pedido
*/
public function setUser(\Project\FrontendBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Project\FrontendBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set notas
*
* #param string $notas
* #return Pedido
*/
public function setNotas($notas)
{
$this->notas = $notas;
return $this;
}
/**
* Get notas
*
* #return string
*/
public function getNotas()
{
return $this->notas;
}
/**
* Set created
*
* #param \DateTime $created
* #return Pedido
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Pedido
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set contentChanged
*
* #param \DateTime $contentChanged
* #return Pedido
*/
public function setContentChanged($contentChanged)
{
$this->contentChanged = $contentChanged;
return $this;
}
/**
* Get contentChanged
*
* #return \DateTime
*/
public function getContentChanged()
{
return $this->contentChanged;
}
/**
* #ORM\PrePersist
*/
public function doStuffOnPrePersist()
{
$this->created = new \DateTime("now");
}
/**
* #ORM\PreUpdate
*/
public function doStuffOnPreUpdate()
{
$this->updated = new \DateTime("now");
}
/**
* Set subtotal
*
* #param float $subtotal
* #return Pedido
*/
public function setSubtotal($subtotal)
{
$this->subtotal = $subtotal;
return $this;
}
/**
* Get subtotal
*
* #return float
*/
public function getSubtotal()
{
return $this->subtotal;
}
/**
* Set iva
*
* #param float $iva
* #return Pedido
*/
public function setIva($iva)
{
$this->iva = $iva;
return $this;
}
/**
* Get iva
*
* #return float
*/
public function getIva()
{
return $this->iva;
}
/**
* Set total
*
* #param float $total
* #return Pedido
*/
public function setTotal($total)
{
$this->total = $total;
return $this;
}
/**
* Get total
*
* #return float
*/
public function getTotal()
{
return $this->total;
}
}
PedidoSubitem:
namespace Project\FrontendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Project\FrontendBundle\Entity\PedidoSubitem
*
* #ORM\Table
* #ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
*/
class PedidoSubitem
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Pedido", inversedBy="PedidoSubitems", cascade={"persist"})
* #ORM\JoinColumn(name="pedido_id", referencedColumnName="id")
**/
private $pedido;
/**
* #ORM\ManyToOne(targetEntity="Subitem", inversedBy="PedidoSubitems", cascade={"persist"})
* #ORM\JoinColumn(name="subitem_id", referencedColumnName="id")
**/
private $subitem;
/**
* #ORM\Column(type="integer", name="number", nullable=false)
*
* #var integer $number
*/
protected $number;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set pedido
*
* #param \Project\FrontendBundle\Entity\Pedido $pedido
* #return PedidoSubitem
*/
public function setPedido(\Project\FrontendBundle\Entity\Pedido $pedido = null)
{
$this->pedido = $pedido;
return $this;
}
/**
* Get pedido
*
* #return \Project\FrontendBundle\Entity\Pedido
*/
public function getPedido()
{
return $this->pedido;
}
/**
* Set subitem
*
* #param \Project\FrontendBundle\Entity\Subitem $subitem
* #return PedidoSubitem
*/
public function setSubitem(\Project\FrontendBundle\Entity\Subitem $subitem = null)
{
$this->subitem = $subitem;
return $this;
}
/**
* Get subitem
*
* #return \Project\FrontendBundle\Entity\Subitem
*/
public function getSubitem()
{
return $this->subitem;
}
/**
* Set integer
*
* #param integer $integer
* #return PedidoSubitem
*/
public function setInteger($integer)
{
$this->integer = $integer;
return $this;
}
/**
* Get integer
*
* #return integer
*/
public function getInteger()
{
return $this->integer;
}
/**
* Set number
*
* #param integer $number
* #return PedidoSubitem
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return integer
*/
public function getNumber()
{
return $this->number;
}
}
Subitem:
namespace Project\FrontendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
//use Vich\UploaderBundle\Mapping\Annotation as Vich;
//use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Project\FrontendBundle\Entity\Subitem
*
* #ORM\Table
* #ORM\Entity
*/
class Subitem
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255, name="nombre")
*/
protected $nombre;
/**
* #ORM\OneToMany(targetEntity="PedidoSubitem", mappedBy="subitem")
**/
private $pedidoSubitems;
/**
* #var integer $position
*
* #ORM\Column(name="position", type="integer")
*/
private $position;
/**
* #ORM\Column(type="string", length=255, name="image_name", nullable=true)
*
* #var string $imageName
*/
protected $imageName;
/**
* #ORM\Column(type="boolean", name="activado", nullable=true)
*
* #var boolean $activado
*/
protected $activado = true;
/**
* #ORM\Column(type="datetime", nullable=true)
*
* #var \DateTime $updatedAt
*/
protected $updatedAt;
/**
* #ORM\Column(type="float", scale=2, name="precio", nullable=true)
*
* #var string $precio
*/
protected $precio;
/**
* #ORM\Column(length=128, unique=true)
*/
private $slug;
public function __construct() {
$this->products = new ArrayCollection();
$this->pedidoSubitems = new ArrayCollection();
}
public function __toString()
{
return $this->nombre;
}
public function getSlug()
{
return $this->slug;
}
/**
* Set position
*
* #param integer $position
* #return Subitem
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* #return integer
*/
public function getPosition()
{
return $this->position;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tipo
*
* #param boolean $tipo
* #return Product
*/
public function setTipo($tipo)
{
$this->tipo = $tipo;
return $this;
}
/**
* Set imageName
*
* #param string $imageName
* #return Subitem
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* Get imageName
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
if($this->image) {
$this->updatedAt = new \DateTime('now');
}
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Product
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set nombre
*
* #param string $nombre
* #return Subitem
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set slug
*
* #param string $slug
* #return Subitem
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Set activado
*
* #param boolean $activado
* #return Subitem
*/
public function setActivado($activado)
{
$this->activado = $activado;
return $this;
}
/**
* Get activado
*
* #return boolean
*/
public function getActivado()
{
return $this->activado;
}
/**
* Set item
*
* #param \Project\FrontendBundle\Entity\Item $item
* #return Subitem
*/
public function setItem(\Project\FrontendBundle\Entity\Item $item)
{
$this->item = $item;
return $this;
}
/**
* Get item
*
* #return \Project\FrontendBundle\Entity\Item
*/
public function getItem()
{
return $this->item;
}
/**
* Add pedidos
*
* #param \Project\FrontendBundle\Entity\Pedido $pedidos
* #return Subitem
*/
public function addPedido(\Project\FrontendBundle\Entity\Pedido $pedidos)
{
$this->pedidos[] = $pedidos;
return $this;
}
/**
* Remove pedidos
*
* #param \Project\FrontendBundle\Entity\Pedido $pedidos
*/
public function removePedido(\Project\FrontendBundle\Entity\Pedido $pedidos)
{
$this->pedidos->removeElement($pedidos);
}
/**
* Get pedidos
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPedidos()
{
return $this->pedidos;
}
/**
* Set precio
*
* #param float $precio
* #return Subitem
*/
public function setPrecio($precio)
{
$this->precio = $precio;
return $this;
}
/**
* Get precio
*
* #return float
*/
public function getPrecio()
{
return $this->precio;
}
/**
* Add subitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $subitems
* #return Subitem
*/
public function addSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $subitems)
{
$this->subitems[] = $subitems;
return $this;
}
/**
* Remove subitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $subitems
*/
public function removeSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $subitems)
{
$this->subitems->removeElement($subitems);
}
/**
* Get subitems
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSubitems()
{
return $this->subitems;
}
/**
* Add pedidoSubitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems
* #return Subitem
*/
public function addPedidoSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems)
{
$this->pedidoSubitems[] = $pedidoSubitems;
return $this;
}
/**
* Remove pedidoSubitems
*
* #param \Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems
*/
public function removePedidoSubitem(\Project\FrontendBundle\Entity\PedidoSubitem $pedidoSubitems)
{
$this->pedidoSubitems->removeElement($pedidoSubitems);
}
/**
* Get pedidoSubitems
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPedidoSubitems()
{
return $this->pedidoSubitems;
}
}
And this type clases:
PedidoType:
namespace Project\FrontendBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Project\FrontendBundle\Form\PedidoSubitemType;
class PedidoType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user')
//->add('pedidoSubitem', 'collection', array('type' => new PedidoSubitemType()))
->add('pedidoSubitems', new PedidoSubitemType())
->add('subtotal')
->add('iva')
->add('total')
->add('notas')
//->add('created')
//->add('updated')
//->add('contentChanged')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\FrontendBundle\Entity\Pedido'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_frontendbundle_pedido';
}
}
PedidoSubitemType:
namespace Project\FrontendBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PedidoSubitemType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('number', 'text')
//->add('pedido')
->add('subitem', 'entity', array('class' => 'ProjectFrontendBundle:Subitem'))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\FrontendBundle\Entity\PedidoSubitem'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_frontendbundle_pedidosubitem';
}
}
I would like to show a form that creates a Pedido form with PedidoSubitem forms embeded.
As you can see in PedidoSubitem I have tried these two codes:
Case A
$builder
->add('user')
->add('pedidoSubitems', new PedidoSubitemType())
The fields related to PedidoSubitemType are shown correctly, but after submitting the form, I get:
Neither the property pedidoSubitems nor one of the methods
addPedidoSubitem(), removePedidoSubitem(), setPedidoSubitems(),
pedidoSubitems(), __set() or __call() exist and have public access in
class "Project\FrontendBundle\Entity\Pedido". (500 Internal
Server Error)
Case B
$builder
->add('user')
->add('pedidoSubitem', 'collection', array('type' => new PedidoSubitemType()))
But when rendering the form ({{ form(form) }}), the fields of PedidoSubitemType are not shown, but just this:
<div>
<label class="required">Pedido subitem</label>
<div id="project_frontendbundle_pedido_pedidoSubitem"></div>
</div>
You need to use Case A, that you've described above but rename field to pedidoSubitem. I mean:
$builder->add('pedidoSubitem', new PedidoSubitemType());
And probably you should rename entity's method addPedido() to addPedidoSubitem().
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();
I have a Form for Product with relation oneToMany with entity ProductLocale and the user can add many ProductLocale as he want.
The rendered form in html seems correct but when I receive the POST array and perform bind() the server response this error:
"ERROR: This value should be of type Wearplay\WearBundle\Entity\ProductLocale.
But I send two ProductLocale entities and validator doesn't recognize them.
It is obvious that the POST request contains a multi-dimensional array that contains the various entities ProductLocale, but the question is why
$form->bindRequest($request)
doesn't work correctly?
Edit #1:
Product Entity
<?php
namespace Wearplay\WearBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*#ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="BrandOwner", cascade="persist")
*/
private $owner;
/**
* #ORM\Column(name="creation_date", type="datetime", nullable=false)
*/
private $creationDate;
/**
* #Assert\Type(type="Wearplay\WearBundle\Entity\ProductLocale")
*/
protected $productLocales;
/**
* #Assert\Type(type="Wearplay\WearBundle\Entity\ProductPic")
*/
protected $productPic;
public function __construct()
{
$this->productLocales = new ArrayCollection();
}
/**
* #ORM\PrePersist
*/
public function createTimestamps()
{
$this->creationDate = new \DateTime(date('Y-m-d H:i:s'));
}
/**
* 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;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Set owner
*
* #param \Wearplay\WearBundle\Entity\BrandOwner $owner
* #return Product
*/
public function setOwner(\Wearplay\WearBundle\Entity\BrandOwner $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return \Wearplay\WearBundle\Entity\BrandOwner
*/
public function getOwner()
{
return $this->owner;
}
/**
* Get ProductLocales
*
* #return \Wearplay\WearBundle\Entity\ProductLocale
*/
public function getProductLocales()
{
return $this->productLocales;
}
/**
* Set ProductLocale
*
* #param \Wearplay\WearBundle\Entity\ProductLocale $productLocale
* #return Product
*/
public function setProductLocales(ArrayCollection $productLocales = null)
{
$this->productLocales = $productLocales;
//return $this->productLocale;
}
/**
* Add ProductLocale
*
* #param ProductLocale $productLocale
*/
/*
public function addProductLocale(ProductLocale $productLocale)
{
$this->productLocales[] = $productLocale;
}
public function removeProductLocale(ProductLocale $productLocale)
{
$this->productLocale->removeElement($productLocale);
}*/
/**
* Get ProductPic
*
* #return \Wearplay\WearBundle\Entity\ProductPic
*/
public function getProductPic()
{
return $this->productPic;
}
/**
* Set ProductPic
*
* #param \Wearplay\WearBundle\Entity\ProductPic $productPic
* #return Product
*/
public function setProductPic(ProductPic $productPic = null)
{
$this->productPic = $productPic;
}
/**
* Add ProductPic
*
* #param ProductPic $productPic
*/
public function addProductPic(ProductPic $productPic)
{
$this->productPic[] = $productPic;
}
}
ProductLocale Entity
<?php
namespace Wearplay\WearBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="product_locale")
*/
class ProductLocale
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Product", cascade="persist")
*/
private $product;
/**
*#ORM\Column(name="market_nation", type="string")
*/
private $marketNation;
/**
* #ORM\Column(type="string")
*/
private $link;
/**
* #ORM\Column(type="decimal", precision=9, scale=2)
*/
private $price;
/**
* #ORM\Column(type="string", length=3)
*/
private $currency;
/**
* #ORM\Column(name="creation_date", type="datetime", nullable=false)
*/
private $creationDate;
/**
* #ORM\PrePersist
*/
/*
public function addProduct(Product $product)
{
if (!$this->product->contains($product)) {
$this->product->add($product);
}
}
*/
public function createTimestamps()
{
$this->creationDate = new \DateTime(date('Y-m-d H:i:s'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set marketNation
*
* #param string $marketNation
* #return ProductLocale
*/
public function setMarketNation($marketNation)
{
$this->marketNation = $marketNation;
return $this;
}
/**
* Get marketNation
*
* #return string
*/
public function getMarketNation()
{
return $this->marketNation;
}
/**
* Set link
*
* #param string $link
* #return ProductLocale
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set price
*
* #param float $price
* #return ProductLocale
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set currency
*
* #param string $currency
* #return ProductLocale
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
* #return ProductLocale
*/
public function setCreationDate($creationDate)
{
$this->creationDate = $creationDate;
return $this;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Set product
*
* #param \Wearplay\WearBundle\Entity\Product $product
* #return ProductLocale
*/
public function setProduct(\Wearplay\WearBundle\Entity\Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \Wearplay\WearBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
}
Solved
Yes #ihsan and #snyx, you're absolutely right, I removed this line:
#Assert\Type(type="Wearplay\WearBundle\Entity\ProductLocale and everything worked perfectly.
I'm sorry for the trivial question but I'm pretty new in Symfony2.