I have a RequestForEstimate entity that at some point in my logic gets to the point where I create a PurchaseOrder and I need to insert a RequestId in the PurchaseOrder table. I have it reference by using the One to One association in doctrine. For some reason the DB call is successful however when I check the table it looks like the request_estimate_id field is null. Here is my logic:
RequestForEstimate entity:
<?php
namespace InboundBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* RequestForEstimate
*
* #ORM\Table(name="request_for_estimate")
* #ORM\Entity(repositoryClass="InboundBundle\Repository\RequestForEstimateRepository")
*/
class RequestForEstimate
{
/**
* #var int
*
* #ORM\Column(name="request_id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="update_time", type="datetime")
*/
private $updateTime;
/**
* #ORM\ManyToOne(targetEntity="RequestStatus", cascade={"persist"})
*/
private $status;
/**
* #ORM\ManyToOne(targetEntity="CoreBundle\Entity\Product")
* #ORM\JoinColumn(name="product_id", referencedColumnName="product_id")
*/
private $product;
/**
* #var int
*
* #ORM\Column(name="quantity", type="integer")
*/
private $quantity = 0;
/**
* #var string
*
* #ORM\Column(name="price_per_unit", type="decimal", precision=10, scale=2)
*/
private $pricePerUnit = 0;
/**
* #var string
*
* #ORM\Column(name="shipping_cost", type="decimal", precision=10, scale=2)
*/
private $shippingCost = 0;
/**
* #var string
*
* #ORM\Column(name="package_cost", type="decimal", precision=10, scale=2)
*/
private $packageCost = 0;
/**
* #var string
*
* #ORM\Column(name="other_fees", type="decimal", precision=10, scale=2)
*/
private $otherFees = 0;
/**
* #var integer
*
* #ORM\Column(name="deposit_required", type="integer")
*/
private $depositRequired = 0;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set product
*
* #param integer $product
*
* #return RequestForEstimate
*/
public function setProduct($product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return int
*/
public function getProduct()
{
return $this->product;
}
/**
* Set quantity
*
* #param integer $quantity
*
* #return RequestForEstimate
*/
public function setQuantity($quantity)
{
$this->quantity = $quantity;
return $this;
}
/**
* Get quantity
*
* #return int
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* Set pricePerUnit
*
* #param string $pricePerUnit
*
* #return RequestForEstimate
*/
public function setPricePerUnit($pricePerUnit)
{
$this->pricePerUnit = $pricePerUnit;
return $this;
}
/**
* Get pricePerUnit
*
* #return string
*/
public function getPricePerUnit()
{
return $this->pricePerUnit;
}
/**
* Set shippingCost
*
* #param string $shippingCost
*
* #return RequestForEstimate
*/
public function setShippingCost($shippingCost)
{
$this->shippingCost = $shippingCost;
return $this;
}
/**
* Get shippingCost
*
* #return string
*/
public function getShippingCost()
{
return $this->shippingCost;
}
/**
* Set otherFees
*
* #param string $otherFees
*
* #return RequestForEstimate
*/
public function setOtherFees($otherFees)
{
$this->otherFees = $otherFees;
return $this;
}
/**
* Get otherFees
*
* #return string
*/
public function getOtherFees()
{
return $this->otherFees;
}
/**
* Set requestId
*
* #param \InboundBundle\Entity\RequestForEstimate $requestId
*
* #return RequestForEstimate
*/
public function setRequestId(\InboundBundle\Entity\RequestForEstimate $requestId = null)
{
$this->requestId = $requestId;
return $this;
}
/**
* Get requestId
*
* #return \InboundBundle\Entity\RequestForEstimate
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Set productId
*
* #param \InboundBundle\Entity\Product $productId
*
* #return RequestForEstimate
*/
public function setProductId(\InboundBundle\Entity\Product $productId = null)
{
$this->productId = $productId;
return $this;
}
/**
* Get productId
*
* #return \InboundBundle\Entity\Product
*/
public function getProductId()
{
return $this->productId;
}
/**
* Constructor
*/
public function __construct()
{
}
/**
* Set depositRequired
*
* #param string $depositRequired
*
* #return RequestForEstimate
*/
public function setDepositRequired($depositRequired)
{
$this->depositRequired = $depositRequired;
return $this;
}
/**
* Get depositRequired
*
* #return string
*/
public function getDepositRequired()
{
return $this->depositRequired;
}
/**
* Set packageCost
*
* #param string $packageCost
*
* #return RequestForEstimate
*/
public function setPackageCost($packageCost)
{
$this->packageCost = $packageCost;
return $this;
}
/**
* Get packageCost
*
* #return string
*/
public function getPackageCost()
{
return $this->packageCost;
}
/**
* Set status
*
* #param \InboundBundle\Entity\RequestStatus $status
*
* #return RequestForEstimate
*/
public function setStatus(\InboundBundle\Entity\RequestStatus $status = null)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return \InboundBundle\Entity\RequestStatus
*/
public function getStatus()
{
return $this->status;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return RequestForEstimate
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return RequestForEstimate
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
}
PurchaseOrder entity:
<?php
namespace InboundBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PurchaseOrder
*
* #ORM\Table(name="purchase_order")
* #ORM\Entity(repositoryClass="InboundBundle\Repository\PurchaseOrderRepository")
*/
class PurchaseOrder
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="RequestForEstimate", cascade={"persist"})
* #ORM\JoinColumn(name="request_estimate_id", referencedColumnName="request_id")
*/
private $requestId;
/**
* #var \DateTime
*
* #ORM\Column(name="create_time", type="datetime")
*/
private $createTime;
/**
* #var \DateTime
*
* #ORM\Column(name="update_time", type="datetime")
*/
private $updateTime;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="ship_date", type="date", nullable=true)
*/
private $shipDate;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set createTime
*
* #param \DateTime $createTime
*
* #return PurchaseOrder
*/
public function setCreateTime($createTime)
{
$this->createTime = $createTime;
return $this;
}
/**
* Get createTime
*
* #return \DateTime
*/
public function getCreateTime()
{
return $this->createTime;
}
/**
* Set updateTime
*
* #param \DateTime $updateTime
*
* #return PurchaseOrder
*/
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
return $this;
}
/**
* Get updateTime
*
* #return \DateTime
*/
public function getUpdateTime()
{
return $this->updateTime;
}
/**
* Set status
*
* #param integer $status
*
* #return PurchaseOrder
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set shipDate
*
* #param \DateTime $shipDate
*
* #return PurchaseOrder
*/
public function setShipDate($shipDate)
{
$this->shipDate = $shipDate;
return $this;
}
/**
* Get shipDate
*
* #return \DateTime
*/
public function getShipDate()
{
return $this->shipDate;
}
/**
* Set requestForEstimate
*
* #param \InboundBundle\Entity\RequestForEstimate $requestForEstimate
*
* #return PurchaseOrder
*/
public function setRequestForEstimate(\InboundBundle\Entity\RequestForEstimate $requestForEstimate = null)
{
$this->requestForEstimate = $requestForEstimate;
return $this;
}
/**
* Get requestForEstimate
*
* #return \InboundBundle\Entity\RequestForEstimate
*/
public function getRequestForEstimate()
{
return $this->requestForEstimate;
}
/**
* Set requestId
*
* #param $requestId
*
* #return PurchaseOrder
*/
public function setRequestId($requestId)
{
$this->request_id = $requestId;
return $this;
}
/**
* Get requestId
*
* #return \InboundBundle\Entity\RequestForEstimate
*/
public function getRequestId()
{
return $this->request_id;
}
}
My controller:
/**
* #Route("request-for-estimate/confirm/{id}", name="request_confirm")
*/
public function confirmRequest(RequestForEstimate $RequestForEstimate)
{
$repo = $this->getDoctrine()->getRepository('InboundBundle:RequestStatus');
$status = $repo->findOneById('6');
$RequestForEstimate->setupdateTime(new \DateTime());
$RequestForEstimate->setstatus($status);
$PurchaseOrder = new PurchaseOrder();
$PurchaseOrder->setRequestId($RequestForEstimate);
$PurchaseOrder->setupdateTime(new \DateTime());
$PurchaseOrder->setcreateTime(new \DateTime());
$PurchaseOrder->setstatus(1);
$em1 = $this->getDoctrine()->getManager();
$em1->persist($PurchaseOrder);
$em1->flush();
$em = $this->getDoctrine()->getManager();
$em->persist($RequestForEstimate);
$em->flush();
return $this->redirectToRoute('requests_for_estimate_view');
}
I will give you an example from one of my projects. The whole trick is in entities setters and cascaders configurations.
Hope it will help.
Entities:
class Agreement
{
// ...
/**
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Requisites", mappedBy="agreement", cascade={"persist"})
*/
private $requisites;
// ...
public function setRequisites(Requisites $requisites = null)
{
$this->requisites = $requisites;
$requisites->setAgreement($this);
return $this;
}
public function getRequisites()
{
return $this->requisites;
}
}
class Requisites
{
// ...
/**
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Agreement", inversedBy="requisites")
* #ORM\JoinColumn(name="Agreement_id", referencedColumnName="id")
*/
private $agreement;
// ...
public function setAgreement(Agreement $agreement = null)
{
$this->agreement = $agreement;
return $this;
}
public function getAgreement()
{
return $this->agreement;
}
}
Controller:
if (null === $agreement->getRequisites()) {
$agreement->setRequisites(new Requisites());
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($agreement);
$entityManager->flush();
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);
}
}
}
First, forgive me for my bad English.
I have a problem with an sql query that I am doing using doctrine in symfony
I have two related tables, one of users and one of actions performed by the user, these tables are related from one to many, a user can do many actions.
I am trying to make a query in which I from all users who have not done an action (the status column is the one that indicates the types of actions, when the process ends it will have an 8) therefore I want to remove those that do not have an 8. In principle, although I have tried many options, what I think would be more correct would be
$query = $em->createQueryBuilder()
->from("BackendBundle:Inscritos", "e")
->select("e")
->innerJoin("BackendBundle:InscritosAcciones", "u", "WITH", "e.id=u.inscritosId")
->groupBy("u.inscritosId")
->where("u.status != 8")
->getQuery();
The fact is that as the user has some other action besides that of status 8 (must have them since it is a process and the actions allow to see what has been happening) I continue to remove that user.
my entities
namespace BackendBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Inscritos
* #UniqueEntity(fields={"correoUsuario"}, message="¡Este correo ya esta registrado!")
* #UniqueEntity(fields={"documento"}, message="¡Este numero de documento ya esta registrado!")
*/
class Inscritos {
/**
* #var integer
*/
private $id;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu nombre")
*/
private $nombreUsuario;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tus apellidos")
*/
private $apellidoUsuario;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Range(
* min = 9,
* max = 9,
* minMessage = "Este campo tiene que tener {{ limit }} numeros ",
* maxMessage = "Este campo tiene que tener {{ limit }} numeros "
* )
*/
private $telefono;
/**
* #var string
* #Assert\Email(checkMX=true)
*/
private $correoUsuario;
/**
* #var string
*/
private $validadocorreo = 'NO';
/**
* #var string
*/
private $tipodocumento;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu numero de documento")
*/
private $documento;
/**
* #var \DateTime
* #Assert\NotBlank(message = "Por favor, escribe tu fecha de nacimiento")
*/
private $fechanacimiento;
/**
* #var string
*/
private $pais;
/**
* #var string
*/
private $provinciaotros;
/**
* #var string
*/
private $municipiootros;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu codigo postal")
*/
private $codigopostal;
/**
* #var string
* #Assert\NotBlank(message = "Por favor, escribe tu direccion de contacto")
*/
private $direccion;
/**
* #var string
*/
private $lugarparticipacion;
/**
* #var \DateTime
*/
private $fechainscritpcion;
/**
* #var string
*/
private $ipinscripcion;
/**
* #var string
*/
private $cadenaseg;
/**
* #var string
*/
private $bloqueo = 'no';
/**
* #var string
*/
private $razonBloqueo;
/**
* #var string
*/
private $perfil;
/**
* #var \DateTime
*/
private $fechaControl;
/**
* #var integer
*/
private $idMunicipio;
/**
* #var integer
*/
private $idProvincia;
/**
* #var string
*/
private $idCcaa;
public function __toString() {
return (string) $this->getId();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set nombreUsuario
*
* #param string $nombreUsuario
*
* #return Inscritos
*/
public function setNombreUsuario($nombreUsuario) {
$this->nombreUsuario = $nombreUsuario;
return $this;
}
/**
* Get nombreUsuario
*
* #return string
*/
public function getNombreUsuario() {
return $this->nombreUsuario;
}
/**
* Set apellidoUsuario
*
* #param string $apellidoUsuario
*
* #return Inscritos
*/
public function setApellidoUsuario($apellidoUsuario) {
$this->apellidoUsuario = $apellidoUsuario;
return $this;
}
/**
* Get apellidoUsuario
*
* #return string
*/
public function getApellidoUsuario() {
return $this->apellidoUsuario;
}
/**
* Set telefono
*
* #param string $telefono
*
* #return Inscritos
*/
public function setTelefono($telefono) {
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return string
*/
public function getTelefono() {
return $this->telefono;
}
/**
* Set correoUsuario
*
* #param string $correoUsuario
*
* #return Inscritos
*/
public function setCorreoUsuario($correoUsuario) {
$this->correoUsuario = $correoUsuario;
return $this;
}
/**
* Get correoUsuario
*
* #return string
*/
public function getCorreoUsuario() {
return $this->correoUsuario;
}
/**
* Set validadocorreo
*
* #param string $validadocorreo
*
* #return Inscritos
*/
public function setValidadocorreo($validadocorreo) {
$this->validadocorreo = $validadocorreo;
return $this;
}
/**
* Get validadocorreo
*
* #return string
*/
public function getValidadocorreo() {
return $this->validadocorreo;
}
/**
* Set tipodocumento
*
* #param string $tipodocumento
*
* #return Inscritos
*/
public function setTipodocumento($tipodocumento) {
$this->tipodocumento = $tipodocumento;
return $this;
}
/**
* Get tipodocumento
*
* #return string
*/
public function getTipodocumento() {
return $this->tipodocumento;
}
/**
* Set documento
*
* #param string $documento
*
* #return Inscritos
*/
public function setDocumento($documento) {
$this->documento = $documento;
return $this;
}
/**
* Get documento
*
* #return string
*/
public function getDocumento() {
return $this->documento;
}
/**
* Set fechanacimiento
*
* #param \DateTime $fechanacimiento
*
* #return Inscritos
*/
public function setFechanacimiento($fechanacimiento) {
$this->fechanacimiento = $fechanacimiento;
return $this;
}
/**
* Get fechanacimiento
*
* #return \DateTime
*/
public function getFechanacimiento() {
return $this->fechanacimiento;
}
/**
* Set pais
*
* #param string $pais
*
* #return Inscritos
*/
public function setPais($pais) {
$this->pais = $pais;
return $this;
}
/**
* Get pais
*
* #return string
*/
public function getPais() {
return $this->pais;
}
/**
* Set provinciaotros
*
* #param string $provinciaotros
*
* #return Inscritos
*/
public function setProvinciaotros($provinciaotros) {
$this->provinciaotros = $provinciaotros;
return $this;
}
/**
* Get provinciaotros
*
* #return string
*/
public function getProvinciaotros() {
return $this->provinciaotros;
}
/**
* Set municipiootros
*
* #param string $municipiootros
*
* #return Inscritos
*/
public function setMunicipiootros($municipiootros) {
$this->municipiootros = $municipiootros;
return $this;
}
/**
* Get municipiootros
*
* #return string
*/
public function getMunicipiootros() {
return $this->municipiootros;
}
/**
* Set codigopostal
*
* #param string $codigopostal
*
* #return Inscritos
*/
public function setCodigopostal($codigopostal) {
$this->codigopostal = $codigopostal;
return $this;
}
/**
* Get codigopostal
*
* #return string
*/
public function getCodigopostal() {
return $this->codigopostal;
}
/**
* Set direccion
*
* #param string $direccion
*
* #return Inscritos
*/
public function setDireccion($direccion) {
$this->direccion = $direccion;
return $this;
}
/**
* Get direccion
*
* #return string
*/
public function getDireccion() {
return $this->direccion;
}
/**
* Set lugarparticipacion
*
* #param string $lugarparticipacion
*
* #return Inscritos
*/
public function setLugarparticipacion($lugarparticipacion) {
$this->lugarparticipacion = $lugarparticipacion;
return $this;
}
/**
* Get lugarparticipacion
*
* #return string
*/
public function getLugarparticipacion() {
return $this->lugarparticipacion;
}
/**
* Set fechainscritpcion
*
* #param \DateTime $fechainscritpcion
*
* #return Inscritos
*/
public function setFechainscritpcion($fechainscritpcion) {
$this->fechainscritpcion = $fechainscritpcion;
return $this;
}
/**
* Get fechainscritpcion
*
* #return \DateTime
*/
public function getFechainscritpcion() {
return $this->fechainscritpcion;
}
/**
* Set ipinscripcion
*
* #param string $ipinscripcion
*
* #return Inscritos
*/
public function setIpinscripcion($ipinscripcion) {
$this->ipinscripcion = $ipinscripcion;
return $this;
}
/**
* Get ipinscripcion
*
* #return string
*/
public function getIpinscripcion() {
return $this->ipinscripcion;
}
/**
* Set cadenaseg
*
* #param string $cadenaseg
*
* #return Inscritos
*/
public function setCadenaseg($cadenaseg) {
$this->cadenaseg = $cadenaseg;
return $this;
}
/**
* Get cadenaseg
*
* #return string
*/
public function getCadenaseg() {
return $this->cadenaseg;
}
/**
* Set bloqueo
*
* #param string $bloqueo
*
* #return Inscritos
*/
public function setBloqueo($bloqueo) {
$this->bloqueo = $bloqueo;
return $this;
}
/**
* Get bloqueo
*
* #return string
*/
public function getBloqueo() {
return $this->bloqueo;
}
/**
* Set razonBloqueo
*
* #param string $razonBloqueo
*
* #return Inscritos
*/
public function setRazonBloqueo($razonBloqueo) {
$this->razonBloqueo = $razonBloqueo;
return $this;
}
/**
* Get razonBloqueo
*
* #return string
*/
public function getRazonBloqueo() {
return $this->razonBloqueo;
}
/**
* Set perfil
*
* #param string $perfil
*
* #return Inscritos
*/
public function setPerfil($perfil) {
$this->perfil = $perfil;
return $this;
}
/**
* Get perfil
*
* #return string
*/
public function getPerfil() {
return $this->perfil;
}
/**
* Set fechaControl
*
* #param \DateTime $fechaControl
*
* #return Inscritos
*/
public function setFechaControl($fechaControl) {
$this->fechaControl = $fechaControl;
return $this;
}
/**
* Get fechaControl
*
* #return \DateTime
*/
public function getFechaControl() {
return $this->fechaControl;
}
/**
* Set idMunicipio
*
* #param integer $idMunicipio
*
* #return Inscritos
*/
public function setIdMunicipio($idMunicipio) {
$this->idMunicipio = $idMunicipio;
return $this;
}
/**
* Get idMunicipio
*
* #return integer
*/
public function getIdMunicipio() {
return $this->idMunicipio;
}
/**
* Set idProvincia
*
* #param integer $idProvincia
*
* #return Inscritos
*/
public function setIdProvincia($idProvincia) {
$this->idProvincia = $idProvincia;
return $this;
}
/**
* Get idProvincia
*
* #return integer
*/
public function getIdProvincia() {
return $this->idProvincia;
}
/**
* Set idCcaa
*
* #param string $idCcaa
*
* #return Inscritos
*/
public function setIdCcaa($idCcaa) {
$this->idCcaa = $idCcaa;
return $this;
}
/**
* Get idCcaa
*
* #return string
*/
public function getIdCcaa() {
return $this->idCcaa;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $imagenes;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $validaInscritos;
/**
* #var \BackendBundle\Entity\Ccaa
*/
private $ccaaInscritos;
/**
* #var \BackendBundle\Entity\Municipios
*/
private $municipioInscritos;
/**
* #var \BackendBundle\Entity\Provincia
*/
private $provinciaInscritos;
/**
* Constructor
*/
public function __construct() {
$this->imagenes = new \Doctrine\Common\Collections\ArrayCollection();
$this->validaInscritos = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add imagene
*
* #param \BackendBundle\Entity\InscritosImages $imagene
*
* #return Inscritos
*/
public function addImagene(\BackendBundle\Entity\InscritosImages $imagene) {
$this->imagenes[] = $imagene;
return $this;
}
/**
* Remove imagene
*
* #param \BackendBundle\Entity\InscritosImages $imagene
*/
public function removeImagene(\BackendBundle\Entity\InscritosImages $imagene) {
$this->imagenes->removeElement($imagene);
}
/**
* Get imagenes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImagenes() {
return $this->imagenes;
}
/**
* Add validaInscrito
*
* #param \BackendBundle\Entity\ValidaInscritos $validaInscrito
*
* #return Inscritos
*/
public function addValidaInscrito(\BackendBundle\Entity\ValidaInscritos $validaInscrito) {
$this->validaInscritos[] = $validaInscrito;
return $this;
}
/**
* Remove validaInscrito
*
* #param \BackendBundle\Entity\ValidaInscritos $validaInscrito
*/
public function removeValidaInscrito(\BackendBundle\Entity\ValidaInscritos $validaInscrito) {
$this->validaInscritos->removeElement($validaInscrito);
}
/**
* Get validaInscritos
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getValidaInscritos() {
return $this->validaInscritos;
}
/**
* Set ccaaInscritos
*
* #param \BackendBundle\Entity\Ccaa $ccaaInscritos
*
* #return Inscritos
*/
public function setCcaaInscritos(\BackendBundle\Entity\Ccaa $ccaaInscritos = null) {
$this->ccaaInscritos = $ccaaInscritos;
return $this;
}
/**
* Get ccaaInscritos
*
* #return \BackendBundle\Entity\Ccaa
*/
public function getCcaaInscritos() {
return $this->ccaaInscritos;
}
/**
* Set municipioInscritos
*
* #param \BackendBundle\Entity\Municipios $municipioInscritos
*
* #return Inscritos
*/
public function setMunicipioInscritos(\BackendBundle\Entity\Municipios $municipioInscritos = null) {
$this->municipioInscritos = $municipioInscritos;
return $this;
}
/**
* Get municipioInscritos
*
* #return \BackendBundle\Entity\Municipios
*/
public function getMunicipioInscritos() {
return $this->municipioInscritos;
}
/**
* Set provinciaInscritos
*
* #param \BackendBundle\Entity\Provincia $provinciaInscritos
*
* #return Inscritos
*/
public function setProvinciaInscritos(\BackendBundle\Entity\Provincia $provinciaInscritos = null) {
$this->provinciaInscritos = $provinciaInscritos;
return $this;
}
/**
* Get provinciaInscritos
*
* #return \BackendBundle\Entity\Provincia
*/
public function getProvinciaInscritos() {
return $this->provinciaInscritos;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $inscritosAcciones;
/**
* Add inscritosAccione
*
* #param \BackendBundle\Entity\InscritosAcciones $inscritosAccione
*
* #return Inscritos
*/
public function addInscritosAccione(\BackendBundle\Entity\InscritosAcciones $inscritosAccione) {
$this->inscritosAcciones[] = $inscritosAccione;
return $this;
}
/**
* Remove inscritosAccione
*
* #param \BackendBundle\Entity\InscritosAcciones $inscritosAccione
*/
public function removeInscritosAccione(\BackendBundle\Entity\InscritosAcciones $inscritosAccione) {
$this->inscritosAcciones->removeElement($inscritosAccione);
}
/**
* Get inscritosAcciones
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getInscritosAcciones() {
return $this->inscritosAcciones;
}
}
entity InscritosAcciones
namespace BackendBundle\Entity;
/**
* InscritosAcciones
*/
class InscritosAcciones
{
/**
* #var integer
*/
private $id;
/**
* #var integer
*/
private $status;
/**
* #var string
*/
private $accion;
/**
* #var string
*/
private $datos;
/**
* #var \DateTime
*/
private $fecha = 'CURRENT_TIMESTAMP';
/**
* #var integer
*/
private $inscritosId;
/**
* #var \BackendBundle\Entity\Inscritos
*/
private $inscritos;
/**
* #var \BackendBundle\Entity\Acciones
*/
private $acciones;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set status
*
* #param integer $status
*
* #return InscritosAcciones
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set accion
*
* #param string $accion
*
* #return InscritosAcciones
*/
public function setAccion($accion)
{
$this->accion = $accion;
return $this;
}
/**
* Get accion
*
* #return string
*/
public function getAccion()
{
return $this->accion;
}
/**
* Set datos
*
* #param string $datos
*
* #return InscritosAcciones
*/
public function setDatos($datos)
{
$this->datos = $datos;
return $this;
}
/**
* Get datos
*
* #return string
*/
public function getDatos()
{
return $this->datos;
}
/**
* Set fecha
*
* #param \DateTime $fecha
*
* #return InscritosAcciones
*/
public function setFecha($fecha)
{
$this->fecha = $fecha;
return $this;
}
/**
* Get fecha
*
* #return \DateTime
*/
public function getFecha()
{
return $this->fecha;
}
/**
* Set inscritosId
*
* #param integer $inscritosId
*
* #return InscritosAcciones
*/
public function setInscritosId($inscritosId)
{
$this->inscritosId = $inscritosId;
return $this;
}
/**
* Get inscritosId
*
* #return integer
*/
public function getInscritosId()
{
return $this->inscritosId;
}
/**
* Set inscritos
*
* #param \BackendBundle\Entity\Inscritos $inscritos
*
* #return InscritosAcciones
*/
public function setInscritos(\BackendBundle\Entity\Inscritos $inscritos = null)
{
$this->inscritos = $inscritos;
return $this;
}
/**
* Get inscritos
*
* #return \BackendBundle\Entity\Inscritos
*/
public function getInscritos()
{
return $this->inscritos;
}
/**
* Set acciones
*
* #param \BackendBundle\Entity\Acciones $acciones
*
* #return InscritosAcciones
*/
public function setAcciones(\BackendBundle\Entity\Acciones $acciones = null)
{
$this->acciones = $acciones;
return $this;
}
/**
* Get acciones
*
* #return \BackendBundle\Entity\Acciones
*/
public function getAcciones()
{
return $this->acciones;
}
}
Both tables are related to other tables but are not necessary in this query. The incritosAcciones table is related to a table of actions, and the one of inscribed with enough tables since it is a quite complex structure.
Regarding what result gives me, because I think I had previously put it, I list all the rows of the inscribed table since they will always have more shares (something in the status field) besides the status = 8
Finally, if in the consultation I group it by
->groupBy("u.status")
I only get (normal) one record for each of the statuses except the one that has status 8
a full consultation would be
$query = $em->createQueryBuilder()
->from("BackendBundle:Inscritos", "e")
->select("e")
->innerJoin("BackendBundle:InscritosAcciones", "u", "WITH", "e.id=u.inscritosId")
->groupBy("u.status")
->where("u.status != 8")
->getQuery();
I have added two screenshots of my phpmyAdmin that you can see in the Spanish version because here I do not have enough reputation to upload images
https://es.stackoverflow.com/questions/132649/problema-para-que-no-salga-un-usuario-en-consulta-onetomany-si-se-da-una-condici
And what they would have to leave are users 43 and 63, nothing would happen because the other users left who do not have any action yet, but the one who should never leave is user 1, who has an action with status 8
Can someone help me please.
Thank you
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'm trying to save two entities linked. Product entity may have any or many entities ProviderRate. When I try to save the product entity, it tells me that ProviderRate related entity has not assigned one of their required fields. I need to save a product with no need to assign a ProviderRate.
The error message showing me is:
Entity of type AppBundle\Entity\ProviderRate is missing an assigned ID for field 'provider'.
The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called.
If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
My entitdades code is as follows:
Product Entity
/**
* Products
*
* #ORM\Table(name="products", uniqueConstraints={#ORM\UniqueConstraint(name="id_producto_UNIQUE", columns={"id"})}, indexes={#ORM\Index(name="fk_id_productos_id_categorias1_idx", columns={"category_id"}), #ORM\Index(name="fk_id_productos_id_producto_tipo1_idx", columns={"type"}), #ORM\Index(name="fk_id_productos_id_moneda1_idx", columns={"currency_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProductsRepository")
*/
class Products {
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
* #Assert\NotBlank(message="Por favor, escriba el nombre del producto.")
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=45, nullable=false)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="description_long", type="text", nullable=false)
*/
private $descriptionLong;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=false)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="weight", type="decimal", precision=11, scale=3, nullable=false)
*/
private $weight;
/**
* #var string
*
* #ORM\Column(name="web", type="string", length=100, nullable=false)
*/
private $web;
/**
* #var boolean
*
* #ORM\Column(name="isActive", type="boolean", nullable=false)
*/
private $isactive;
/**
* #var \DateTime
*
* #ORM\Column(name="createdtime", type="datetime", nullable=false)
* #Assert\DateTime()
*/
private $createdtime;
/**
* #var \DateTime
*
* #ORM\Column(name="modifiedtime", type="datetime", nullable=false)
* #Assert\DateTime()
*/
private $modifiedtime;
/**
* #var \DateTime
*
* #ORM\Column(name="deletedtime", type="datetime", nullable=true)
*/
private $deletedtime;
/**
* #var boolean
*
* #ORM\Column(name="isDeleted", type="boolean", nullable=false)
*/
private $isdeleted;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \AppBundle\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* #var \AppBundle\Entity\ProductTypes
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\ProductTypes")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="type", referencedColumnName="id")
* })
*/
private $type;
/**
* #var \AppBundle\Entity\Currencies
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Currencies")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="currency_id", referencedColumnName="id")
* })
*/
private $currency;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Sets", inversedBy="product")
* #ORM\JoinTable(name="products_sets",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="set_id", referencedColumnName="id")
* }
* )
*/
private $set;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Products", mappedBy="productParentid")
*/
private $product;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Documents", inversedBy="product")
* #ORM\JoinTable(name="product_attachments",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="document_id", referencedColumnName="id")
* }
* )
*/
private $document;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Images", inversedBy="product")
* #ORM\JoinTable(name="products_images",
* joinColumns={
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="image_id", referencedColumnName="id")
* }
* )
*/
private $image;
// CUSTOM CODE
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\ProviderRate", mappedBy="product", cascade={"persist"})
*/
private $providerRate;
/**
* Constructor
*/
public function __construct() {
$this->createdtime = new \DateTime();
$this->modifiedtime = new \DateTime();
$this->set = new \Doctrine\Common\Collections\ArrayCollection();
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
$this->document = new \Doctrine\Common\Collections\ArrayCollection();
$this->image = new \Doctrine\Common\Collections\ArrayCollection();
$this->providerRate = new \Doctrine\Common\Collections\ArrayCollection();
$this->descriptionLong = '';
$this->amountPerUnit = 1;
$this->web = '';
$this->weight = 0;
$this->isdeleted = 0;
}
/**
* Set name
*
* #param string $name
* #return Products
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Products
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* Set code
*
* #param string $code
* #return Products
*/
public function setCode($code) {
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode() {
return $this->code;
}
/**
* Set descriptionLong
*
* #param string $descriptionLong
* #return Products
*/
public function setDescriptionLong($descriptionLong) {
$this->descriptionLong = $descriptionLong;
return $this;
}
/**
* Get descriptionLong
*
* #return string
*/
public function getDescriptionLong() {
return $this->descriptionLong;
}
/**
* Set amountPerUnit
*
* #param integer $amountPerUnit
* #return Products
*/
public function setAmountPerUnit($amountPerUnit) {
$this->amountPerUnit = $amountPerUnit;
return $this;
}
/**
* Get amountPerUnit
*
* #return integer
*/
public function getAmountPerUnit() {
return $this->amountPerUnit;
}
/**
* Set weight
*
* #param string $weight
* #return Products
*/
public function setWeight($weight) {
$this->weight = $weight;
return $this;
}
/**
* Get weight
*
* #return string
*/
public function getWeight() {
return $this->weight;
}
/**
* Set web
*
* #param string $web
* #return Products
*/
public function setWeb($web) {
$this->web = $web;
return $this;
}
/**
* Get web
*
* #return string
*/
public function getWeb() {
return $this->web;
}
/**
* Set isactive
*
* #param boolean $isactive
* #return Products
*/
public function setIsactive($isactive) {
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return boolean
*/
public function getIsactive() {
return $this->isactive;
}
/**
* Set createdtime
*
* #param \DateTime $createdtime
* #return Products
*/
public function setCreatedtime($createdtime) {
$this->createdtime = $createdtime;
return $this;
}
/**
* Get createdtime
*
* #return \DateTime
*/
public function getCreatedtime() {
return $this->createdtime;
}
/**
* Set modifiedtime
*
* #param \DateTime $modifiedtime
* #return Products
*/
public function setModifiedtime($modifiedtime) {
$this->modifiedtime = $modifiedtime;
return $this;
}
/**
* Get modifiedtime
*
* #return \DateTime
*/
public function getModifiedtime() {
return $this->modifiedtime;
}
/**
* Set deletedtime
*
* #param \DateTime $deletedtime
* #return Products
*/
public function setDeletedtime($deletedtime) {
$this->deletedtime = $deletedtime;
return $this;
}
/**
* Get deletedtime
*
* #return \DateTime
*/
public function getDeletedtime() {
return $this->deletedtime;
}
/**
* Set isdeleted
*
* #param boolean $isdeleted
* #return Products
*/
public function setIsdeleted($isdeleted) {
$this->isdeleted = $isdeleted;
return $this;
}
/**
* Get isdeleted
*
* #return boolean
*/
public function getIsdeleted() {
return $this->isdeleted;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set category
*
* #param \AppBundle\Entity\Categories $category
* #return Products
*/
public function setCategory(\AppBundle\Entity\Categories $category = null) {
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\Categories
*/
public function getCategory() {
return $this->category;
}
/**
* Set type
*
* #param \AppBundle\Entity\ProductTypes $type
* #return Products
*/
public function setType(\AppBundle\Entity\ProductTypes $type = null) {
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return \AppBundle\Entity\ProductTypes
*/
public function getType() {
return $this->type;
}
/**
* Set currency
*
* #param \AppBundle\Entity\Currencies $currency
* #return Products
*/
public function setCurrency(\AppBundle\Entity\Currencies $currency = null) {
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return \AppBundle\Entity\Currencies
*/
public function getCurrency() {
return $this->currency;
}
/**
* Add set
*
* #param \AppBundle\Entity\Sets $set
* #return Products
*/
public function addSet(\AppBundle\Entity\Sets $set) {
$this->set[] = $set;
return $this;
}
/**
* Remove set
*
* #param \AppBundle\Entity\Sets $set
*/
public function removeSet(\AppBundle\Entity\Sets $set) {
$this->set->removeElement($set);
}
/**
* Get set
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSet() {
return $this->set;
}
/**
* Add product
*
* #param \AppBundle\Entity\Products $product
* #return Products
*/
public function addProduct(\AppBundle\Entity\Products $product) {
$this->product[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\Products $product
*/
public function removeProduct(\AppBundle\Entity\Products $product) {
$this->product->removeElement($product);
}
/**
* Get product
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProduct() {
return $this->product;
}
/**
* Add document
*
* #param \AppBundle\Entity\Documents $document
* #return Products
*/
public function addDocument(\AppBundle\Entity\Documents $document) {
$this->document[] = $document;
return $this;
}
/**
* Remove document
*
* #param \AppBundle\Entity\Documents $document
*/
public function removeDocument(\AppBundle\Entity\Documents $document) {
$this->document->removeElement($document);
}
/**
* Get document
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDocument() {
return $this->document;
}
/**
* Add image
*
* #param \AppBundle\Entity\Images $image
* #return Products
*/
public function addImage(\AppBundle\Entity\Images $image) {
$this->image[] = $image;
return $this;
}
/**
* Remove image
*
* #param \AppBundle\Entity\Images $image
*/
public function removeImage(\AppBundle\Entity\Images $image) {
$this->image->removeElement($image);
}
/**
* Get image
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImage() {
return $this->image;
}
// CUSTOM CODE
/**
* Set providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
* #return Products
*/
/* public function setProviderRate(\AppBundle\Entity\ProviderRate $providerRate = null)
{
$this->providerRate = $providerRate;
return $this;
}
*/
/**
* Add providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
* #return Products
*/
public function addProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
$this->providerRate[] = $providerRate;
return $this;
}
/**
* Remove providerRate
*
* #param \AppBundle\Entity\ProviderRate $providerRate
*/
public function removeProviderRate(\AppBundle\Entity\ProviderRate $providerRate) {
$this->providerRate->removeElement($providerRate);
}
/**
* Get providerRate
*
* #return \AppBundle\Entity\ProviderRate
*/
public function getProviderRate()
{
return $this->providerRate;
}
}
ProviderRate Entity
/**
* ProviderRate
*
* #ORM\Table(name="provider_rate", indexes={#ORM\Index(name="fk_proveedor_has_producto_compra_producto_compra1_idx", columns={"product_id"}), #ORM\Index(name="fk_id_tarifa_proveedor_id_moneda1_idx", columns={"currency_id"}), #ORM\Index(name="IDX_3A645C45A53A8AA", columns={"provider_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\ProviderRateRepository")
*/
class ProviderRate
{
/**
* #var string
*
* #ORM\Column(name="reference", type="string", length=45, nullable=false)
*/
private $reference;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="amount_per_unit", type="integer", nullable=true)
*/
private $amountPerUnit;
/**
* #var string
*
* #ORM\Column(name="unit_price", type="decimal", precision=25, scale=3, nullable=false)
*/
private $unitPrice;
/**
* #var string
*
* #ORM\Column(name="discount", type="decimal", precision=25, scale=3, nullable=false)
*/
private $discount;
/**
* #var \AppBundle\Entity\Providers
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Providers")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="provider_id", referencedColumnName="id")
* })
*/
private $provider;
/**
* #var \AppBundle\Entity\Products
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Products", inversedBy="providerRate")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id")
*
*/
private $product;
/**
* Set provider
*
* #param \AppBundle\Entity\Providers $provider
* #return ProviderRate
*/
public function setProvider(\AppBundle\Entity\Providers $provider)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return \AppBundle\Entity\Providers
*/
public function getProvider()
{
return $this->provider;
}
/**
* Set product
*
* #param \AppBundle\Entity\Products $product
* #return ProviderRate
*/
public function setProduct(\AppBundle\Entity\Products $product)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \AppBundle\Entity\Products
*/
public function getProduct()
{
return $this->product;
}
}
The code to run on the controller is as follows:
public function ajaxNewProductAction() {
$request = $this->getRequest();
$product = new Products();
$form = $this->createForm(new ProductsType(), $product);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
$em = $this->getDoctrine()->getManager();
$providerId = $request->get('provider');
$productVals = $request->get('Products');
$currency = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");
$product->setCurrency($currency);
$product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
$product->setIsactive(1);
$em->persist($product);
$em->flush();
$response['success'] = true;
$response['data'] = 0;
$response['providerId'] = $providerId;
}
else {
$response['success'] = false;
$response['cause'] = 'whatever';
}
return new JsonResponse($response);
}
return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
}
SOLVE:
I can solve it. The code of my entities thats ok. I change the controller function.
First I create the product object, set the providerRate to null and them persist it.
After I create the providerRate object and set the product object.
public function ajaxNewProductAction() {
$request = $this->getRequest();
$product = new Products();
$form = $this->createForm(new ProductsType(), $product);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isSubmitted() && $form->isValid()) { // Se procesa el formulario
$em = $this->getDoctrine()->getManager();
$providerId = $request->get('provider');
$productVal = $request->get('Products');
$currency = $em->getRepository('AppBundle:Currencies')->findOneByName("Euro");
$product->setCurrency($currency);
$product->setType($em->getRepository('AppBundle:ProductTypes')->findOneById(1));
$product->setProviderRate(null);
$em->persist($product);
$em->flush();
$providerRate = new ProviderRate();
$providerRate->setProvider($em->getRepository('AppBundle:Providers')->findOneById($providerId));
$providerRate->setProduct($product);
$providerRate->setReference($productVal["providerRate"][1]["reference"]);
$providerRate->setName($productVal["name"]);
$providerRate->setDescription($productVal["description"]);
$providerRate->setAmountPerUnit(1);
$providerRate->setUnitPrice(0);
$providerRate->setDiscount(0);
$providerRate->setCurrency($currency);
$providerRate->setProduct($product);
$em->persist($providerRate);
$em->flush();
$response['success'] = true;
}
else {
$response['success'] = false;
$response['cause'] = 'Algo ocurrió';
}
return new JsonResponse($response);
}
return $this->render(':products/ajax:newProduct.html.twig', array("form" => $form->createView(), "edit" => false));
}
I'm trying to solve my problem but after many hours of search, It doesn't work :(
So I've got a class :
<?php
namespace Application\HappyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Bar
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Application\HappyBundle\Entity\BarRepository")
*/
class Bar
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="name", type="string", length=45)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255)
*/
private $address;
/**
* #var string
*
* #ORM\Column(name="addressComplete", type="string", length=255)
*/
private $addressComplete;
/**
* #var string
*
* #ORM\Column(name="postal_code", type="string", length=5, nullable=true)
*/
private $postalCode;
/**
* #var string
*
* #ORM\Column(name="town", type="string", length=45)
*/
private $town;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=45)
*/
private $country;
/**
* #var string
*
* #ORM\Column(name="latitude", type="string", length=20)
*/
private $latitude;
/**
* #var string
*
* #ORM\Column(name="longitude", type="string", length=20)
*/
private $longitude;
/**
* #var array
*
* #ORM\Column(name="validate", type="boolean", nullable=false)
*/
private $validate;
/**
* #var \DateTime
*
* #ORM\Column(name="last_update", type="datetime", nullable=true)
*/
private $lastUpdate;
/**
* #var ArrayCollection of AssocBarDay
* #Assert\Valid
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\AssocBarDay", mappedBy="bar" , cascade={"persist" , "remove"})
*/
private $day;
/**
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\AssocBarDrink", mappedBy="drink", cascade={"persist"})
*/
private $drink;
/**
* #ORM\OneToMany(targetEntity="Application\HappyBundle\Entity\Bar", mappedBy="barVersionned", cascade={"persist"})
*/
private $barHaveVersions;
/**
* #ORM\ManyToOne(targetEntity="Application\HappyBundle\Entity\Bar", inversedBy="barHaveVersions" , cascade={"persist"})
*/
private $barVersionned;
/**
* Constructor
*/
public function __construct()
{
$this->day = new \Doctrine\Common\Collections\ArrayCollection();
$this->drink = new \Doctrine\Common\Collections\ArrayCollection();
$this->validate = false;
$this->lastUpdate = new \DateTime('now');
}
public function __toString(){
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Bar
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set address
*
* #param string $address
* #return Bar
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set postalCode
*
* #param string $postalCode
* #return Bar
*/
public function setPostalCode($postalCode)
{
$this->postalCode = $postalCode;
return $this;
}
/**
* Get postalCode
*
* #return string
*/
public function getPostalCode()
{
return $this->postalCode;
}
/**
* Set town
*
* #param string $town
* #return Bar
*/
public function setTown($town)
{
$this->town = $town;
return $this;
}
/**
* Get town
*
* #return string
*/
public function getTown()
{
return $this->town;
}
/**
* Set country
*
* #param string $country
* #return Bar
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set latitude
*
* #param string $latitude
* #return Bar
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* #return string
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* #param string $longitude
* #return Bar
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* #return string
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Add drink
*
* #param \Application\HappyBundle\Entity\AssocBarDrink $drink
* #return Bar
*/
public function addDrink(\Application\HappyBundle\Entity\AssocBarDrink $drink)
{
$this->drink[] = $drink;
return $this;
}
/**
* Remove drink
*
* #param \Application\HappyBundle\Entity\AssocBarDrink $drink
*/
public function removeDrink(\Application\HappyBundle\Entity\AssocBarDrink $drink)
{
$this->drink->removeElement($drink);
}
/**
* Get drink
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDrink()
{
return $this->drink;
}
/**
* Add day
*
* #param \Application\HappyBundle\Entity\AssocBarDay $day
* #return Bar
*/
public function addDay(\Application\HappyBundle\Entity\AssocBarDay $day)
{
$this->day[] = $day;
return $this;
}
/**
* Remove day
*
* #param \Application\HappyBundle\Entity\AssocBarDay $day
*/
public function removeDay(\Application\HappyBundle\Entity\AssocBarDay $day)
{
$this->day->removeElement($day);
}
/**
* Get day
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDay()
{
return $this->day;
}
/**
* Set lastUpdate
*
* #param \DateTime $lastUpdate
* #return Bar
*/
public function setLastUpdate($lastUpdate)
{
$this->lastUpdate = $lastUpdate;
return $this;
}
/**
* Get lastUpdate
*
* #return \DateTime
*/
public function getLastUpdate()
{
return $this->lastUpdate;
}
/**
* Set validate
*
* #param boolean $validate
* #return Bar
*/
public function setValidate($validate)
{
$this->validate = $validate;
return $this;
}
/**
* Get validate
*
* #return boolean
*/
public function getValidate()
{
return $this->validate;
}
/**
* Add barHaveVersions
*
* #param \Application\HappyBundle\Entity\Bar $barHaveVersions
* #return Bar
*/
public function addBarHaveVersion(\Application\HappyBundle\Entity\Bar $barHaveVersions)
{
$this->barHaveVersions[] = $barHaveVersions;
return $this;
}
/**
* Remove barHaveVersions
*
* #param \Application\HappyBundle\Entity\Bar $barHaveVersions
*/
public function removeBarHaveVersion(\Application\HappyBundle\Entity\Bar $barHaveVersions)
{
$this->barHaveVersions->removeElement($barHaveVersions);
}
/**
* Get barHaveVersions
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBarHaveVersions()
{
return $this->barHaveVersions;
}
/**
* Set barVersionned
*
* #param \Application\HappyBundle\Entity\Bar $barVersionned
* #return Bar
*/
public function setBarVersionned(\Application\HappyBundle\Entity\Bar $barVersionned = null)
{
$this->barVersionned = $barVersionned;
return $this;
}
/**
* Get barVersionned
*
* #return \Application\HappyBundle\Entity\Bar
*/
public function getBarVersionned()
{
return $this->barVersionned;
}
/**
* Set addressComplete
*
* #param string $addressComplete
* #return Bar
*/
public function setAddressComplete($addressComplete)
{
$this->addressComplete = $addressComplete;
return $this;
}
/**
* Get addressComplete
*
* #return string
*/
public function getAddressComplete()
{
return $this->addressComplete;
}
}
and OneToMany with this class:
<?php
namespace Application\HappyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* AssocBarDayHappyHour
* #ORM\Table(name="assoc_bar_day")
* #ORM\Entity(repositoryClass="Application\HappyBundle\Entity\AssocBarDayRepository")
*/
class AssocBarDay
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Application\HappyBundle\Entity\Bar", inversedBy="day" , cascade={"persist"})
*/
private $bar;
/**
* #var array
* #ORM\Column(name="day", type="array", nullable=true)
*/
private $day;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_start_happy_hour", type="time", nullable=true)
*/
private $timeStartHappyHour;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_end_happy_hour", type="time", nullable=true)
*/
private $timeEndHappyHour;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_bar_open", type="time", nullable=true)
*/
private $timeBarOpen;
/**
* #var \DateTime
* #Assert\Time()
* #ORM\Column(name="time_bar_close", type="time" , nullable=true)
*/
private $timeBarClose;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set timeStartHappyHour
*
* #param \DateTime $timeStartHappyHour
* #return AssocBarDay
*/
public function setTimeStartHappyHour($timeStartHappyHour)
{
$this->timeStartHappyHour = $timeStartHappyHour;
return $this;
}
/**
* Get timeStartHappyHour
*
* #return \DateTime
*/
public function getTimeStartHappyHour()
{
return $this->timeStartHappyHour;
}
/**
* Set timeEndHappyHour
*
* #param \DateTime $timeEndHappyHour
* #return AssocBarDay
*/
public function setTimeEndHappyHour($timeEndHappyHour)
{
$this->timeEndHappyHour = $timeEndHappyHour;
return $this;
}
/**
* Get timeEndHappyHour
*
* #return \DateTime
*/
public function getTimeEndHappyHour()
{
return $this->timeEndHappyHour;
}
/**
* Set timeBarOpen
*
* #param \DateTime $timeBarOpen
* #return AssocBarDay
*/
public function setTimeBarOpen($timeBarOpen)
{
$this->timeBarOpen = $timeBarOpen;
return $this;
}
/**
* Get timeBarOpen
*
* #return \DateTime
*/
public function getTimeBarOpen()
{
return $this->timeBarOpen;
}
/**
* Set timeBarClose
*
* #param \DateTime $timeBarClose
* #return AssocBarDay
*/
public function setTimeBarClose($timeBarClose)
{
$this->timeBarClose = $timeBarClose;
return $this;
}
/**
* Get timeBarClose
*
* #return \DateTime
*/
public function getTimeBarClose()
{
return $this->timeBarClose;
}
/**
* Set bar
*
* #param \Application\HappyBundle\Entity\Bar $bar
* #return AssocBarDay
*/
public function setBar(\Application\HappyBundle\Entity\Bar $bar = null)
{
$this->bar = $bar;
return $this;
}
/**
* Get bar
*
* #return \Application\HappyBundle\Entity\Bar
*/
public function getBar()
{
return $this->bar;
}
/**
* Set day
*
* #param array $day
* #return AssocBarDay
*/
public function setDay($day)
{
$this->day = $day;
return $this;
}
/**
* Get day
*
* #return array
*/
public function getDay()
{
return $this->day;
}
}
So when I post my form, the Assert of the Collection of days doesn't block when time is empty?
I put correctly the:
#Assert\Valid
Over day Collection and
#Assert\Time()
of each property of AssocBarDay
:( anyone I've got an idea?
Thanks for your help.
The reason is almost all of the validation constraints will not return invalid for empty/null values.
Just have a look at the TimeValidator's validate method ...
if (null === $value || '' === $value || $value instanceof \DateTime) {
return;
}
Therefore you will need to add the #Assert\NotBlank constraint additionally to have empty values generate a validation error for that property.
NotBlank
Validates that a value is not blank, defined as not equal to a blank
string and also not equal to null.