How do i solve Semantical error: "Class has no association named.." - php

i am following part 5 of the symblog symfony2 tutorial:
http://tutorial.symblog.co.uk/docs/customising-the-view-more-with-twig.html
under heading: The Homepage - Blogs and Comments
when i get to update:
// src/Blogger/BlogBundle/Repository/BlogRepositoy.php
public function getLatestBlogs($limit = null)
{
$qb = $this->createQueryBuilder('b')
->select('b, c')
->leftJoin('b.comments', 'c')
->addOrderBy('b.created', 'DESC');
if (false === is_null($limit))
$qb->setMaxResults($limit);
return $qb->getQuery()
->getResult();
}
and also when i update:
{# src/Blogger/BlogBundle/Resources/views/Page/index.html.twig #}
{# .. #}
<footer class="meta">
<p>Comments: {{ blog.comments|length }}</p>
<p>Posted by <span class="highlight">{{ blog.author }}</span> at {{ blog.created|date('h:iA') }}</p>
<p>Tags: <span class="highlight">{{ blog.tags }}</span></p>
</footer>
{# .. #}
i then refresh my browser and get error:
[Semantical Error] line 0, col 71 near 'c ORDER BY b.created': Error: Class
Blogger\BlogBundle\Entity\Blog has no association named comments
500 Internal Server Error - QueryException
<?php
// src/Blogger/BlogBundle/Entity/Blog.php
namespace Blogger\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="Blogger\BlogBundle\Repository\BlogRepository")
* #ORM\Table(name="blog")
* #ORM\HasLifecycleCallbacks()
*/
class Blog
{
public function __toString()
{
return $this->getTitle();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $title;
/**
* #ORM\Column(type="string", length=100)
*/
protected $author;
/**
* #ORM\Column(type="text")
*/
protected $blog;
/**
* #ORM\Column(type="string", length="20")
*/
protected $image;
/**
* #ORM\Column(type="text")
*/
protected $tags;
protected $comments;
/**
* #ORM\Column(type="datetime")
*/
protected $created;
/**
* #ORM\Column(type="datetime")
*/
protected $updated;
public function __construct()
{
$this->comments = new ArrayCollection();
$this->setCreated(new \DateTime());
$this->setUpdated(new \DateTime());
}
public function setUpdatedValue()
{
$this->setUpdated(new \DateTime());
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set blog
*
* #param text $blog
*/
public function setBlog($blog)
{
$this->blog = $blog;
}
/**
* Get blog
*
* #return text
*/
public function getBlog($length = null)
{
if (false === is_null($length) && $length > 0)
return substr($this->blog, 0, $length);
else
return $this->blog;
}
/**
* Set image
*
* #param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set tags
*
* #param text $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* Get tags
*
* #return text
*/
public function getTags()
{
return $this->tags;
}
/**
* Set created
*
* #param datetime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param datetime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* Get updated
*
* #return datetime
*/
public function getUpdated()
{
return $this->updated;
}
}
please help solve this. i dont know where i went wrong
thanks

You didn't paste the src/Blogger/BlogBundle/Entity/Blog.php file. It would help resolving your issue.
Most probably you didn't add comments field to your entity (or didn't annotate it properly).
Similar problem: Doctrine2: What is wrong with the association between these entities?
EDIT: Now when you pasted your entity I can see the comments field is not annotated. Doctrine's entity manager doesn't know anything about it. You have to provide mapping (in your case via annotations).
EDIT 2:
In your entity you should have (src/Blogger/BlogBundle/Entity/Blog.php):
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="blog")
*/
protected $comments;
but you have:
protected $comments;
Mapping is missing. Doctrine doesn't know how to use your field.

I have also followed the symblog tutorial. My blog.php file is as follows:
<?php
namespace Blogger\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Blogger\BlogBundle\Entity\Blog
*/
class Blog
{
/**
* #var integer $id
*/
private $id;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #var string $title
*/
private $title;
/**
* #var string $author
*/
private $author;
/**
* #var string $blog
*/
private $blog;
/**
* #var string $image
*/
private $image;
/**
* #var string $tags
*/
private $tags;
/**
* #var string $comment
*/
private $comment;
/**
* #var datetime $created
*/
private $created;
/**
* #var datetime $updated
*/
private $updated;
public function __construct()
{
$this->comments = new ArrayCollection();
$this->setCreated(new \DateTime());
$this->setUpdated(new \DateTime());
}
/**
* Set title
*
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
$this->setSlug($this->title);
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set blog
*
* #param string $blog
*/
public function setBlog($blog)
{
$this->blog = $blog;
}
/**
* Get blog
*
* #return string
*/
public function getBlog($length = null)
{
if (false === is_null($length) && $length > 0)
return substr($this->blog, 0, $length);
else
return $this->blog;
}
/**
* Set image
*
* #param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set tags
*
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set comment
*
* #param string $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set created
*
* #param datetime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param datetime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* Get updated
*
* #return datetime
*/
public function getUpdated()
{
return $this->updated;
}
public function addComment(Comment $comment)
{
$this->comments[] = $comment;
}
public function getComments()
{
return $this->comments;
}
/**
* #ORM\preUpdate
*/
public function setUpdatedValue()
{
$this->setUpdated(new \DateTime());
}
/**
* #var Blogger\BlogBundle\Entity\Comment
*/
private $comments;
public function __toString()
{
return $this->getTitle();
}
/**
* #var string $slug
*/
protected $slug;
/**
* Set slug
*
* #param string $slug
*/
public function setSlug($slug)
{
$this->slug = $this->slugify($slug);
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
public function slugify($text)
{
$text = preg_replace('#[^\\pL\d]+#u', '-', $text);
$text = trim($text, '-');
if (function_exists('iconv'))
{
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
$text = strtolower($text);
$text = preg_replace('#[^-\w]+#', '', $text);
if (empty($text))
{
return 'n-a';
}
return $text;
} }
Hope this helps you.
Your code is missing
/**
* #var Blogger\BlogBundle\Entity\Comment
*/
private $comments;

Related

Error with mass flush objects doctrine

This causes an error:
$em = $this->getDoctrine()->getManager();
$courses = $em->getRepository(Course::class)->findBy(['id' => $ids]);
foreach ($courses as $course) {
$data = $form->getData();
$course->setProperties($data);
$em->persist($course);
}
$em->flush();
The followin error is thown:
Type error:
Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::
__construct() must be of the type array, null given, called in:
/var/www/bib/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1064
But when I insert $em->flush(); In a cycle - everything works.
What wrong?
Course entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use CoreBundle\Entity\GuidTrait;
use CoreBundle\Entity\Typo3Trait;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
use CoreBundle\Entity\LoggableTrait;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\CourseRepository")
* #ORM\Table(name="courses")
* #ORM\HasLifecycleCallbacks()
*/
class Course
{
use GuidTrait, Typo3Trait, Timestampable, LoggableTrait;
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
/**
* #ORM\Column(type="string", length=150, nullable=true)
*/
protected $title;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string")
*/
protected $code;
/**
* #Assert\NotBlank()
* #ORM\Column(name="`order`", type="integer")
*/
protected $order;
/**
* #Assert\NotBlank()
* #ORM\Column(type="smallint")
*/
protected $status;
/**
* #Assert\NotBlank()
* #Assert\DateTime()
* #ORM\Column(type="datetime", nullable=false)
*/
protected $date;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $enrolmentDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $durationDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $timetable;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactName;
/**
* #Assert\NotBlank()
* #Assert\Email
* #ORM\Column(type="string", nullable=false)
*/
protected $contactEmail;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactPhone;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $contactFax;
/**
* #Assert\NotBlank()
* #Assert\Type(type="float")
* #Assert\GreaterThanOrEqual(0)
*
* #ORM\Column(type="decimal", precision=8, scale=2, nullable=false)
*/
protected $price;
/**
* #Assert\NotBlank()
* #Assert\GreaterThanOrEqual(0)
* #Assert\Type(type="integer")
*
* #ORM\Column(type="integer", nullable=false)
*/
protected $availability;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $courseNotes;
/**
* #ORM\ManyToOne(targetEntity="Centre", inversedBy="courses")
* #ORM\JoinColumn(name="centre_id", referencedColumnName="uid")
*/
protected $centre;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Qualification", inversedBy="courses")
* #ORM\JoinColumn(name="qualification_id", referencedColumnName="uid",onDelete="CASCADE")
*/
protected $qualification;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Venue", inversedBy="courses")
* #ORM\JoinColumn(name="venue_id", referencedColumnName="uid")
*/
protected $venue;
/**
* #ORM\OneToMany(targetEntity="Booking", mappedBy="course", cascade={"remove"})
*/
protected $bookings;
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $reference;
public function __construct()
{
$this->status = self::STATUS_ACTIVE;
$this->code = 'CODE';
$this->order = 1;
}
/**
* #ORM\PreFlush
*/
public function updateReference()
{
$q = $this->getQualification()->getCode();
$c = $this->getCentre()->getCode();
$v = $this->getVenue()->getCode();
$d = $this->getDate()->format('d/m/Y');
$this->setReference("$q - $c - $v - $d");
}
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param $title
* #return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* #return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* #param $code
* #return $this
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #return mixed
*/
public function getOrder()
{
return $this->order;
}
/**
* #param $order
* #return $this
*/
public function setOrder($order)
{
$this->order = $order;
return $this;
}
/**
* #return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* #param $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param $date
* #return $this
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* #return mixed
*/
public function getEnrolmentDetails()
{
return $this->enrolmentDetails;
}
/**
* #param $enrolmentDetails
* #return $this
*/
public function setEnrolmentDetails($enrolmentDetails)
{
$this->enrolmentDetails = $enrolmentDetails;
return $this;
}
/**
* #return mixed
*/
public function getDurationDetails()
{
return $this->durationDetails;
}
/**
* #param $durationDetails
* #return $this
*/
public function setDurationDetails($durationDetails)
{
$this->durationDetails = $durationDetails;
return $this;
}
/**
* #return mixed
*/
public function getTimetable()
{
return $this->timetable;
}
/**
* #param $timetable
* #return $this
*/
public function setTimetable($timetable)
{
$this->timetable = $timetable;
return $this;
}
/**
* #return mixed
*/
public function getContactName()
{
return $this->contactName;
}
/**
* #param $contactName
* #return $this
*/
public function setContactName($contactName)
{
$this->contactName = $contactName;
return $this;
}
/**
* #return mixed
*/
public function getContactEmail()
{
return $this->contactEmail;
}
/**
* #param $contactEmail
* #return $this
*/
public function setContactEmail($contactEmail)
{
$this->contactEmail = $contactEmail;
return $this;
}
/**
* #return mixed
*/
public function getContactPhone()
{
return $this->contactPhone;
}
/**
* #param $contactPhone
* #return $this
*/
public function setContactPhone($contactPhone)
{
$this->contactPhone = $contactPhone;
return $this;
}
/**
* #return mixed
*/
public function getContactFax()
{
return $this->contactFax;
}
/**
* #param $contactFax
* #return $this
*/
public function setContactFax($contactFax)
{
$this->contactFax = $contactFax;
return $this;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param $price
* #return $this
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* #return mixed
*/
public function getAvailability()
{
return $this->availability;
}
/**
* #param $availability
* #return $this
*/
public function setAvailability($availability)
{
$this->availability = $availability;
return $this;
}
/**
* #return mixed
*/
public function getCourseNotes()
{
return $this->courseNotes;
}
/**
* #param $courseNotes
* #return $this
*/
public function setCourseNotes($courseNotes)
{
$this->courseNotes = $courseNotes;
return $this;
}
/**
* #return mixed
*/
public function getCentre()
{
return $this->centre;
}
/**
* #param $centre
* #return $this
*/
public function setCentre($centre)
{
$this->centre = $centre;
return $this;
}
/**
* #return mixed
*/
public function getQualification()
{
return $this->qualification;
}
/**
* #param $qualification
* #return $this
*/
public function setQualification($qualification)
{
$this->qualification = $qualification;
return $this;
}
/**
* #return mixed
*/
public function getVenue()
{
return $this->venue;
}
/**
* #param $venue
* #return $this
*/
public function setVenue($venue)
{
$this->venue = $venue;
return $this;
}
/**
* #return mixed
*/
public function getReference()
{
return $this->reference;
}
/**
* #param $reference
* #return $this
*/
public function setReference($reference)
{
$this->reference = $reference;
return $this;
}
/**
* #return mixed
*/
public function getBookings()
{
return $this->bookings;
}
/**
* #param mixed $bookings
*/
public function setBookings($bookings)
{
$this->bookings = $bookings;
}
public function getVat( $amount = 0 )
{
if (empty($amount)) {
return round( $this->price * $this->centre->getVat()->getRate()/100, 2 );
} else {
return round( $amount * $this->centre->getVat()->getRate()/100, 2 );
}
}
public function setProperties(Course $course)
{
foreach ($this as $key=>$value) {
if ($course->$key) {
$this->$key = $course->$key;
}
}
}
}
There is nothing supernatural in this entity.
Does anyone have an answer to the question I asked?
There are many issues in Symfony and Doctrine when you execute the flush() method. For example, calling flush() inside a Doctrine listener is not a supported Doctrine usage. it means you are trying to nest several flushes inside each other, which can indeed break the unit of work.
There is a really complete examplample in this StackOverflow Answer, but I think it maybe not be enaugh to understand your problem, so if you want you can check all the posible scenarios where flush should fail here:
https://github.com/doctrine/doctrine2/issues/4004

symfony 2 Fixtures for many to many relationship

How to set up fixtures for symfony 2 in for many to many relationship,
Following 2 entities are made by command lines,
And then added some lines for many to many relationship
Entity 1: Blog Class
<?php
namespace Acme\MainBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Blog
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\MainBundle\Entity\BlogRepository")
*/
class Blog {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="tag", inversedBy="blogs")
* #ORM\JoinTable(name="blog_tag",
* joinColumns={#ORM\JoinColumn(name="blog_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="tag_id", referencedColumnName="id")}
* )
**/
protected $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="subTitle", type="text")
*/
private $subTitle;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var boolean
*
* #ORM\Column(name="isPublished", type="boolean")
*/
private $isPublished;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Blog
*/
public function setTitle($title) {
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* Set author
*
* #param string $author
* #return Blog
*/
public function setAuthor($author) {
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor() {
return $this->author;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Blog
*/
public function setCreatedAt($createdAt) {
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt() {
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Blog
*/
public function setUpdatedAt($updatedAt) {
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt() {
return $this->updatedAt;
}
/**
* Set content
*
* #param string $content
* #return Blog
*/
public function setContent($content) {
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent() {
return $this->content;
}
/**
* Set isPublished
*
* #param boolean $isPublished
* #return Blog
*/
public function setIsPublished($isPublished) {
$this->isPublished = $isPublished;
return $this;
}
/**
* Get isPublished
*
* #return boolean
*/
public function getIsPublished() {
return $this->isPublished;
}
public function __toString() {
return strval($this->id);
}
/**
* Set subTitle
*
* #param string $subTitle
* #return Blog
*/
public function setSubTitle($subTitle)
{
$this->subTitle = $subTitle;
return $this;
}
/**
* Get subTitle
*
* #return string
*/
public function getSubTitle()
{
return $this->subTitle;
}
/**
* Add tags
*
* #param \Acme\MainBundle\Entity\tag $tags
* #return Blog
*/
public function addTag(\Acme\MainBundle\Entity\tag $tags)
{
$this->tags[] = $tags;
$tags->addBlog($this);
return $this;
}
/**
* Remove tags
*
* #param \Acme\MainBundle\Entity\tag $tags
*/
public function removeTag(\Acme\MainBundle\Entity\tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Get tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
}
Entity 2: Tag Class
<?php
namespace Acme\MainBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Tag
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\MainBundle\Entity\TagRepository")
*/
class Tag {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="blog", mappedBy="tags")
**/
protected $blogs;
/**
* #var string
*
* #ORM\Column(name="tag", type="string", length=255)
*/
private $tag;
/**
* #var boolean
*
* #ORM\Column(name="isPublished", type="boolean")
*/
private $isPublished;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Tag
*/
public function setTag($tag) {
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag() {
return $this->tag;
}
/**
* Set isPublished
*
* #param boolean $isPublished
* #return Tag
*/
public function setIsPublished($isPublished) {
$this->isPublished = $isPublished;
return $this;
}
/**
* Get isPublished
*
* #return boolean
*/
public function getIsPublished() {
return $this->isPublished;
}
public function __toString() {
return strval($this->id);
}
/**
* Constructor
*/
public function __construct()
{
$this->blogs = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add blogs
*
* #param \Acme\MainBundle\Entity\blog $blogs
* #return Tag
*/
public function addBlog(\Acme\MainBundle\Entity\blog $blogs)
{
$this->blogs[] = $blogs;
$blogs->addTag($this);
return $this;
}
/**
* Remove blogs
*
* #param \Acme\MainBundle\Entity\blog $blogs
*/
public function removeBlog(\Acme\MainBundle\Entity\blog $blogs)
{
$this->blogs->removeElement($blogs);
}
/**
* Get blogs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBlogs()
{
return $this->blogs;
}
}
Attention!!!
You have a circular reference in your code!!!
When you add a tag to a blog, it call add blog to tag and so on, please fix it in like this:
Blog
/**
* Add tags
*
* #param \Acme\MainBundle\Entity\tag $tags
* #return Blog
*/
public function addTag(\Acme\MainBundle\Entity\tag $tags)
{
if (!$this->tags->contains($tags))
{
$this->tags[] = $tags;
$tags->addBlog($this);
}
return $this;
}
Tag
/**
* Add blogs
*
* #param \Acme\MainBundle\Entity\blog $blogs
* #return Tag
*/
public function addBlog(\Acme\MainBundle\Entity\blog $blogs)
{
if (!$this->blogs->contains($blogs))
{
$this->blogs[] = $blogs;
$blogs->addTag($this);
}
return $this;
}
For your question:
First, install and configure the DoctrineFixturesBundle.
Use the ordered fixture features to load first the tag then the blog.
Then I write for you this example fixtures:
TagFixtures
<?php
namespace Acme\MainBundle\DataFixtures\ORM;
use Acme\MainBundle Bundle\Entity\Tag;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
class TagFixtures extends AbstractFixture implements OrderedFixtureInterface {
/**
* Load data fixtures with the passed EntityManager
*
* #param \Doctrine\Common\Persistence\ObjectManager $manager
*/
function load(ObjectManager $manager)
{
$tag1 = new Tag();
$tag1->setTag("tag name 1");
$tag1->setIsPublished(true);
$tag2 = new Tag();
$tag2->setTag("tag name 2");
$tag2->setIsPublished(true);
$manager->persist($tag1);
$manager->persist($tag2);
$this->addReference('tag-tag_1', $tag1);
$this->addReference('tag-tag_2', $tag2);
$manager->flush();
}
/**
* Get the order of this fixture
*
* #return integer
*/
function getOrder()
{
return 1;
}
}
BlogFixtures
<?php
namespace Acme\MainBundle\DataFixtures\ORM;
use Acme\MainBundle\Entity\Blog;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
class BlogFixtures extends AbstractFixture implements OrderedFixtureInterface {
/**
* Load data fixtures with the passed EntityManager
*
* #param \Doctrine\Common\Persistence\ObjectManager $manager
*/
function load(ObjectManager $manager)
{
$blog = new Blog();
$blog->setTitle('Happy new year');
$blog->setAuthor("me");
$blog->setIsPublished(true);
$blog->setContent("Happy new year");
$blog->setSubTitle("2015");
$blog->setCreatedAt(new \DateTime('now'));
$blog->setUpdatedAt(new \DateTime('now'));
$blog->addTag($this->getReference('tag-tag_1'));
// $blog->addTag($this->getReference('tag-tag_2'));
$manager->persist($blog);
// $this->addReference('blog-blog_1', $blog);
$manager->flush();
}
/**
* Get the order of this fixture
*
* #return integer
*/
function getOrder()
{
return 2;
}
}
Hope this help and happy new year!
For simple cases I create my fixtures like:
Acme/DemoBundle/Entity/Tag.php
public function addBlog(\Acme\MainBundle\Entity\blog $blog)
{
$this->blogs[] = $blog;
return $this;
}
Acme/DemoBundle/Entity/Blog.php
public function addTag(\Acme\MainBundle\Entity\tag $tags)
{
$this->tags[] = $tags;
$tags->addBlog($this);
return $this;
}
Acme/DemoBundle/DataFixtures/ORM/TagBlogFixture.php
class TagBlogFixture extends AbstractFixture implements OrderedFixtureInterface {
function load(ObjectManager $manager)
{
$tag1 = new Tag();
// setters
$tag2 = new Tag();
// setters
$blog1 = new Blog();
// setters
$blog1
->addTag($tag1)
->addTag($tag2)
;
$blog2 = new Blog();
// setters
$blog2->addTag($tag2);
$manager->persist($tag1);
$manager->persist($tag2);
$manager->persist($blog1);
$manager->persist($blog2);
$manager->flush();
}
function getOrder()
{
return 1;
}
}
This doesn't share any references between objects, creates them in single file..

Select entities where referenced objects property is equals value

Right now i try to wrap my head around Doctrine2.
So i have the following structure:
I have an article entity:
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="article")
*/
class Article extends BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="ArticleRevision", mappedBy="article", cascade={"persist"})
* #var ArrayCollection
*/
private $articleRevisions;
/**
* #ORM\ManyToOne(targetEntity="ArticleRevision")
* #ORM\JoinColumn(name="currentRevisionId", referencedColumnName="id", nullable=true)
* #var ArticleRevision
*/
private $currentRevision;
public function __construct(array $options = null) {
$this->articleRevisions = new ArrayCollection();
parent::__construct($options);
}
/**
* #return int
*/
public function getId() {
return $this->id;
}
/**
* #param int $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #param ArticleRevision $articleRevision
*/
public function addArticleRevision($articleRevision) {
$this->articleRevisions[] = $articleRevision;
$articleRevision->setArticle($this);
}
/**
* #return ArrayCollection
*/
public function getArticleRevisions() {
return $this->articleRevisions;
}
/**
* #return ArticleRevision
*/
public function getCurrentRevision() {
return $this->currentRevision;
}
/**
* #param ArticleRevision $articleRevision
*/
public function setCurrentRevision($articleRevision) {
$this->currentRevision = $articleRevision;
}
}
that has articleRevisions and references its current revision:
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="articlerevision")
*/
class ArticleRevision extends BaseEntity {
const TYPE_RELEASE = "release";
const TYPE_DRAFT = "draft";
const TYPE_AUTOSAVE = "autosave";
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
* #var int
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumn(name="categoryId", referencedColumnName="id")
* #var Category
**/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Article", inversedBy="articleRevisions")
* #ORM\JoinColumn(name="articleId", referencedColumnName="id")
* #var Article
**/
private $article;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $urlParam;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $copyright;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $supertitle;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $title;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $teaser;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $text;
/**
* #ORM\ManyToOne(targetEntity="ArticleRevision")
* #ORM\JoinColumn(name="previousRevisionId", referencedColumnName="id", nullable=true)
* #var ArticleRevision
*/
private $previousRevision;
public function __construct(array $options = null) {
parent::__construct($options);
}
/**
* #return int
*/
public function getId() {
return $this->id;
}
/**
* #param int $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #return Category
*/
public function getCategory() {
return $this->category;
}
/**
* #param Category $category
*/
public function setCategory($category){
$this->category = $category;
}
/**
* #return Article
*/
public function getArticle() {
return $this->article;
}
/**
* #param Article $article
*/
public function setArticle($article) {
$this->article = $article;
}
/**
* #return string
*/
public function getCopyright() {
return $this->copyright;
}
/**
* #param string $copyright
*/
public function setCopyright($copyright) {
$this->copyright = $copyright;
}
/**
* #return string
*/
public function getUrlParam() {
return $this->urlParam;
}
/**
* #param string $urlParam
*/
public function setUrlParam($urlParam) {
$this->urlParam = $urlParam;
}
/**
* #return string
*/
public function getSupertitle() {
return $this->supertitle;
}
/**
* #param string $supertitle
*/
public function setSupertitle($supertitle) {
$this->supertitle = $supertitle;
}
/**
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* #param string $title
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* #return string
*/
public function getTeaser() {
return $this->teaser;
}
/**
* #param string $teaser
*/
public function setTeaser($teaser) {
$this->teaser = $teaser;
}
/**
* #return string
*/
public function getText() {
return $this->text;
}
/**
* #param string $text
*/
public function setText($text) {
$this->text = $text;
}
/**
* #return ArticleRevision
*/
public function getPreviousRevision() {
return $this->previousRevision;
}
/**
* #param ArticleRevision $previousRevision
*/
public function setPreviousRevision($previousRevision) {
$this->previousRevision = $previousRevision;
}
}
What i am trying to achieve is to select every article, where the categoryId of the currentRevision is for example 1.
I've tried:
$qb = $this->getRepository()->createQueryBuilder('a');
$qb->leftJoin('a.currentRevision', 'r')
->where('r.category = :category')
->setParameters(array('category' => $category));
return $qb->getQuery()->getResult();
Where $category is an int or the Application\Entity\Category. Both is returning an empty array. Can you point me in the right direction?
Any help is appreciated!
EDIT
Ouput of $qb->__toString():
SELECT a FROM Application\Entity\Article a LEFT JOIN a.currentRevision
r WHERE r.category = :category
r.category = :category, reference to Entity Category not to scalar field, you should join also Category and change condition to something like that:
$qb = $this->getRepository()->createQueryBuilder('a');
$qb->leftJoin('a.currentRevision', 'r')
->leftJoin('r.category', 'c')
->where('c.id = :category')
->setParameters(array('category' => $category));
return $qb->getQuery()->getResult();

FatalErrorException: Error: Call to a member function getId() on a non-object in ...PostListener.php line 20

I'm new in Symfony2. I've a task to create blog. One of the necessary is displaying most popular posts. So I think that the best varient is create listener. It will be call, when visiter will read post. And listener will increment onŠµ of the fild in database(MySQL). I create method in repository, which makes selection by this field. And also create Action, which renders posts by this selection. But when I try to read post, a have error:
FatalErrorException: Error: Call to a member function getId() on a non-object in /var/www/blo/src/Blog/Bundle/BlogBundle/EventListener/PostVisitedListener.php line 20.
Please, help me.
This my Entity (Post):
namespace Blog\Bundle\BlogBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Post
*
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="Blog\Bundle\BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank
* #Assert\Length(min="13", max="255")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=100)
* #Assert\NotBlank
* #Assert\Length(min="13", max="100")
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="post", type="text")
* #Assert\NotBlank
* #Assert\Length(min="100")
*/
private $post;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=100)
*/
private $image;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="createdAt", type="datetime")
*
*/
private $createdAt;
/**
*
* #ORM\Column(name="tags", type="text")
*/
private $tags;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
*/
private $category;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
/**
* #var integer
*
* #ORM\Column(name="visitedIncrement", type="integer")
*/
private $visitedIncrement;
public function __construct()
{
$this->comments = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
* #return Post
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set post
*
* #param string $post
* #return Post
*/
public function setPost($post)
{
$this->post = $post;
return $this;
}
/**
* Get post
*
* #return string
*/
public function getPost()
{
return $this->post;
}
/**
* Set image
*
* #param string $image
* #return Post
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set tags
*
* #param string $tags
* #return Post
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set category
*
* #param $category
* #return $this
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return integer
*/
public function getCategory()
{
return $this->category;
}
/**
* Set comments
*
* #param string $comments
* #return Post
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
/**
* Get comments
*
* #return string
*/
public function getComments()
{
return $this->comments;
}
/**
* #param \DateTime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param int $visitedIncrement
*/
public function setVisitedIncrement($visitedIncrement)
{
$this->visitedIncrement = $visitedIncrement;
return $this;
}
/**
* #return int
*/
public function getVisitedIncrement()
{
return $this->visitedIncrement;
}
public function __toString()
{
return $this->getTitle();
}
}
This is my PostRepository
public function visitedIncrement($id)
{
$query = $this->getEntityManager()
->createQuery(
'UPDATE BlogBlogBundle:Post p
SET p.visitedIncrement = p.visitedIncrement + 1
WHERE p.id = :post_id')
->setParameter(':post_id', $id);
$query->execute();
This is my PostVisitedEvent
namespace Blog\Bundle\BlogBundle\Event;
use Blog\Bundle\BlogBundle\Entity\Post;
use Symfony\Component\EventDispatcher\Event;
class PostVisitedEvent extends Event
{
protected $post;
/**
* #param Post $post
*/
public function setPost(Post $post)
{
return $this->post;
}
/**
* #return Post
*/
public function getPost()
{
return $this->post;
}
}
This is my PostVisitedListener
namespace Blog\Bundle\BlogBundle\EventListener;
use Blog\Bundle\BlogBundle\Entity\PostRepository;
use Doctrine\ORM\EntityManager;
use Blog\Bundle\BlogBundle\Event\PostVisitedEvent;
class PostVisitedListener
{
protected $repository;
public function __construct(PostRepository $repository)
{
$this->repository = $repository;
}
public function onPostVisited(PostVisitedEvent $event)
{
$this->repository->visitedIncrement($event->getPost()->getId());
}
This is my Action (it opens post and gives a opportunity to create comment):
public function showPostAction($id)
{
$postRepository = $this->container->get('blog_blog_bundle.post.repository');
$post = $postRepository->find($id);
if (!$post) {
throw $this->createNotFoundException('The post is not found!');
}
$commentRepository = $this->container->get('blog_blog_bundle.comment.repository');
$comments = $commentRepository->findCommentForPost($post->getId());
$event = new PostVisitedEvent();
$event->setPost($post);
$eventDispatcher = $this->get('event_dispatcher');
$eventDispatcher->dispatch('blog_blog_bundle.post_visited', $event);
return $this->render('BlogBlogBundle:Default:showPost.html.twig', array(
'post' => $post,
'comments' => $comments,
));
}
Yuo can see, that I also create services for repositories and listener. There are:
service id="blog_blog_bundle.post.repository" class="Blog\Bundle\BlogBundle\Entity\PostRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument>BlogBlogBundle:Post argument
service
service id="blog_blog_bundle.comment.repository" class="Blog\Bundle\BlogBundle\Entity\CommentRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument BlogBlogBundle:Comment argument
service
service id="blog_blog_bundle.post_visited_listener" class="Blog\Bundle\BlogBundle\EventListener\PostVisitedListener"
argument type="service" id="blog_blog_bundle.post.repository"
tag name="kernel.event_listener" event="blog_blog_bundle.post_visited" method="onPostVisited"
service
Please, help me.
public function onPostVisited(PostVisitedEvent $event)
{
if (!($event->getPost() instanceof PostInterface)) return;
$this->repository->visitedIncrement($event->getPost()->getId());
}
PostInterface is not a symfony interface. You have to code it. Asking for interface is better than asking for a concrete instance because symfony sometimes uses proxy classes instead of concrete classes.

Class seems not to be a managed Doctrine entity. Did you forget to map it?

What I'm trying to do is to get an Post(Post Entity) form where I can select a featured picture from another entity(File Entity).
At the end I would like to display only the files of type "featured Image" but even if I remove my query_builder I've got a exception that says:
Class "Site\Backend\Adminbundle\Entity\File" seems not to be a managed Doctrine entity. Did you forget to map it?
Here is my PostType form
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title')
->add('thumb', 'entity', array(
'class' => 'Site\Backend\Adminbundle\Entity\File',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('f')
//->where('f.state = :state')
//->setParameter('state', $prms['state'])
->orderBy('f.dateUpdated', 'DESC');
}
))
}
In the other hand I have my two entities:
Here is my File entity
<?php
namespace Site\Backend\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Site\Backend\AdminBundle\Entity\File
*
* #ORM\Table()
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class File {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreated", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="dateUpdated", type="datetime")
*/
private $dateUpdated;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* #ORM\Column(type="string", length=255)
*/
public $path;
/**
* #ORM\ManyToOne(targetEntity="TypeFile", inversedBy="files")
*/
private $type;
/**
* #var string
*
* #ORM\OneToMany(targetEntity="Site\Backend\BlogBundle\Entity\Post", mappedBy="thumb")
*/
private $posts;
public function __construct() {
$this->setDateCreated(new \DateTime());
$this->setDateUpdated(new \DateTime());
$this->type = new ArrayCollection();
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload() {
$this->setDateUpdated(new \DateTime());
if (null !== $this->file) {
// do whatever you want to generate a unique name
$this->path = sha1(uniqid(mt_rand(), true)) . '.' . $this->file->guessExtension();
} else {
//throwException($e);
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload() {
if (null === $this->file) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
if ($file = $this->getAbsolutePath()) {
if (file_exists($file)) {
unlink($file);
}
}
}
public function getAbsolutePath() {
return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
}
public function getWebPath() {
return null === $this->path ? null : './' . $this->getUploadDir() . '/' . $this->path;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir() {
// get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
return 'uploads/' . $this->type;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath() {
return $this->path;
}
public function __toString() {
return $this->name;
}
/**
* Add type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
* #return File
*/
public function addType(\Site\Backend\AdminBundle\Entity\TypeFile $type) {
$this->type[] = $type;
return $this;
}
/**
* Remove type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
*/
public function removeType(\Site\Backend\AdminBundle\Entity\TypeFile $type) {
$this->type->removeElement($type);
}
/**
* Get type
*
* #return Doctrine\Common\Collections\Collection
*/
public function getType() {
return $this->type;
}
/**
* Set type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
* #return File
*/
public function setType(\Site\Backend\AdminBundle\Entity\TypeFile $type = null) {
$this->type = $type;
return $this;
}
public function getFile() {
return $this->file;
}
public function setFile($file) {
$this->file = $file;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return File
*/
public function setDateCreated($dateCreated) {
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated() {
return $this->dateCreated;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return File
*/
public function setDateUpdated($dateUpdated) {
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated() {
return $this->dateUpdated;
}
/**
* Add posts
*
* #param \Site\Backend\BlogBundle\Entity\Post $posts
* #return File
*/
public function addPost(\Site\Backend\BlogBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \Site\Backend\BlogBundle\Entity\Post $posts
*/
public function removePost(\Site\Backend\BlogBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
And Here is my Post entity
<?php
namespace Site\Backend\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreated", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="dateUpdated", type="datetime")
*/
private $dateUpdated;
/**
* #var \DateTime
*
* #ORM\Column(name="datePublished", type="datetime", nullable=true)
*/
private $datePublished;
/**
* #var string
*
* #ORM\Column(name="state", type="string", length=255)
*/
private $state;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var Author
* #ORM\ManyToOne(targetEntity="Site\Backend\AdminBundle\Entity\User", inversedBy="posts")
*/
private $author;
/**
* #var Thumb
* #ORM\ManyToOne(targetEntity="Site\Backend\AdminBundle\Entity\File", inversedBy="posts")
*/
private $thumb;
/**
* #var Comments
* #ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
/**
* #var Categories
* #ORM\ManyToMany(targetEntity="Category", cascade={"persist"})
*/
private $categories;
/**
* #var Tags
* #ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
*/
private $tags;
/**
* Constructeur
*/
public function __construct()
{
$this->setDateCreated(new \DateTime());
$this->setDateUpdated(new \DateTime());
$this->comments = new ArrayCollection();
$this->Categories = new ArrayCollection();
$this->tags = new ArrayCollection();
}
public function __toString(){
return $this->title;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return Comment
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return Comment
*/
public function setDateUpdated($dateUpdated)
{
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->dateUpdated;
}
/**
* Get datePublished
*
* #return \DateTime
*/
public function getDatePublished()
{
return $this->datePublished;
}
/**
* Set datePublished
*
* #param \DateTime $datePublished
* #return Comment
*/
public function setDatePublished($datePublished)
{
$this->datePublished = $datePublished;
return $this;
}
/**
* Set state
*
* #param string $state
* #return Post
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string
*/
public function getState()
{
return $this->state;
}
/**
* Set content
*
* #param string $content
* #return Post
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set author
*
* #param \Site\Backend\AdminBundle\Entity\User $author
* #return Post
*/
public function setAuthor(\Site\Backend\AdminBundle\Entity\User $author = null)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return \Site\Backend\AdminBundle\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
/**
* Add comments
*
* #param \Site\Backend\BlogBundle\Entity\Comment $comments
* #return Post
*/
public function addComment(\Site\Backend\BlogBundle\Entity\Comment $comments)
{
$this->comments[] = $comments;
return $this;
}
/**
* Remove comments
*
* #param \Site\Backend\BlogBundle\Entity\Comment $comments
*/
public function removeComment(\Site\Backend\BlogBundle\Entity\Comment $comments)
{
$this->comments->removeElement($comments);
}
/**
* Get comments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategory(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories[] = $category;
return $this;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategoriesNew(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories[] = $category;
return $this;
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategory(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategoriesNew(\Site\Backend\BlogBundle\Entity\Category $category)
{
}
/**
* Get Categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Get Categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategoriesNew()
{
//return $this->categories;
}
/**
* Add tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
* #return Post
*/
public function addTag(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Add tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
* #return Post
*/
public function addTagsNew(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Site\Backend\BlogBundle\Entity\Tag $tags
*/
public function removeTag(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Remove Tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
*/
public function removeTagsNew(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
//$this->tags->removeElement($tags);
}
/**
* Get Tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
/**
* Get Tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTagsNew()
{
//return $this->Tags;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategorie(\Site\Backend\BlogBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategorie(\Site\Backend\BlogBundle\Entity\Category $categories)
{
$this->categories->removeElement($categories);
}
/**
* #ORM\preUpdate
*/
public function setUpdateValue(){
$this->setDateUpdated(new \DateTime());
}
/**
* Set thumb
*
* #param \Site\Backend\AdminBundle\Entity\File $thumb
* #return Post
*/
public function setThumb(\Site\Backend\AdminBundle\Entity\File $thumb = null)
{
$this->thumb = $thumb;
return $this;
}
/**
* Get thumb
*
* #return \Site\Backend\AdminBundle\Entity\File
*/
public function getThumb()
{
return $this->thumb;
}
}
Thanks in advance
I hope I was clear, if It is not the case please tell me.
Try changing:
Site\Backend\Adminbundle\Entity\File
to
Site\Backend\AdminBundle\Entity\File
An other way to resolve the case :
->add('thumb', null, array(
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('f')
->select('f')
->leftJoin('f.type', 't')
->where('t.name = :type')
->setParameter('type', 'Featured Images')
->orderBy('f.dateUpdated', 'DESC');
}
))
In case you are working with multiple connections, you might have forgotten to map your bundle. Make sure it's the case in app/config/config.yml:
orm:
entity_managers:
default:
mappings:
AppBundle: ~
SiteBackendAdminBundle: ~
Or if you want to split in several entity managers:
orm:
entity_managers:
default:
mappings:
AppBundle: ~
admin:
mappings:
SiteBackendAdminBundle: ~
Documentation Symfony/Doctrine: Multiple Entity Managers.

Categories