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..
Related
In editAction method of controller I tried to edit existed entities in class table inheritance.
But after form submit I get error:
Neither the property "id" nor one of the methods
"addId()"/"removeId()", "setId()", "id()", "__set()" or "__call()"
exist and have public access in class "AdBundle\Entity\AdFlat".
Why AdFlat entity not extended of AdBase entity?
Base entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdBase
*
* #ORM\Table(name="ad_base")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdBaseRepository")
* #ORM\HasLifecycleCallbacks()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
"flat" = "AdFlat"
* })
*/
abstract class AdBase
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdCategory")
*/
private $category;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Field Location should not be blank")
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank(message="Not specified Title")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Assert\NotBlank(message="Not specified Description")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="ad")
*/
private $photos;
/**
* #ORM\Column(type="float")
* #Assert\NotBlank()
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdPriceType")
*/
private $priceType;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean")
*/
private $visible = false;
/**
* #ORM\Column(type="boolean")
*/
private $active = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set author
*
* #param string $author
*
* #return AdBase
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Set title
*
* #param string $title
*
* #return AdBase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return AdBase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set photos
*
* #param string $photos
*
* #return AdBase
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
/**
* Get photos
*
* #return string
*/
public function getPhotos()
{
return $this->photos;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getPriceType()
{
return $this->priceType;
}
/**
* #param mixed $priceType
*/
public function setPriceType($priceType)
{
$this->priceType = $priceType;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return AdBase
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param string $updatedAt
*
* #return AdBase
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set visible
*
* #param boolean $visible
*
* #return AdBase
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #ORM\PrePersist()
*/
public function prePersist()
{
$this->author = 'voodoo';
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->location = 'Donetsk';
}
/**
* #ORM\PreUpdate()
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
Extended entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdFlat
*
* #ORM\Table(name="ad_flat")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdFlatRepository")
*/
class AdFlat extends AdBase
{
/**
* #var integer
*
* #ORM\Column(type="integer")
* #Assert\NotBlank(message="ad_flat.rooms.not_blank")
*/
private $rooms;
/**
* #var float
*
* #ORM\Column(name="square", type="float", nullable=true)
*/
private $square;
/**
* #var float
*
* #ORM\Column(name="liveSquare", type="float", nullable=true)
*/
private $liveSquare;
/**
* #var float
*
* #ORM\Column(type="float", nullable=true)
*/
private $kitchenSquare;
/**
* #var int
*
* #ORM\Column(name="floor", type="integer")
*/
private $floor;
/**
* #var int
*
* #ORM\Column(name="floors", type="integer")
*/
private $floors;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWallType")
*/
private $wallType;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWCType")
*/
private $wcType;
/**
* #return mixed
*/
public function getRooms()
{
return $this->rooms;
}
/**
* #param mixed $rooms
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
}
/**
* Set square
*
* #param float $square
*
* #return AdFlat
*/
public function setSquare($square)
{
$this->square = $square;
return $this;
}
/**
* Get square
*
* #return float
*/
public function getSquare()
{
return $this->square;
}
/**
* Set liveSquare
*
* #param float $liveSquare
*
* #return AdFlat
*/
public function setLiveSquare($liveSquare)
{
$this->liveSquare = $liveSquare;
return $this;
}
/**
* Get liveSquare
*
* #return float
*/
public function getLiveSquare()
{
return $this->liveSquare;
}
/**
* #return float
*/
public function getKitchenSquare()
{
return $this->kitchenSquare;
}
/**
* #param float $kitchenSquare
*/
public function setKitchenSquare($kitchenSquare)
{
$this->kitchenSquare = $kitchenSquare;
}
/**
* Set floor
*
* #param integer $floor
*
* #return AdFlat
*/
public function setFloor($floor)
{
$this->floor = $floor;
return $this;
}
/**
* Get floor
*
* #return int
*/
public function getFloor()
{
return $this->floor;
}
/**
* Set floors
*
* #param integer $floors
*
* #return AdFlat
*/
public function setFloors($floors)
{
$this->floors = $floors;
return $this;
}
/**
* Get floors
*
* #return int
*/
public function getFloors()
{
return $this->floors;
}
/**
* Set wallType
*
* #param string $wallType
*
* #return AdFlat
*/
public function setWallType($wallType)
{
$this->wallType = $wallType;
return $this;
}
/**
* Get wallType
*
* #return string
*/
public function getWallType()
{
return $this->wallType;
}
/**
* Set wcType
*
* #param string $wcType
*
* #return AdFlat
*/
public function setWcType($wcType)
{
$this->wcType = $wcType;
return $this;
}
/**
* Get wcType
*
* #return string
*/
public function getWcType()
{
return $this->wcType;
}
}
In controller:
public function editAction(Request $request)
{
$adId = $request->get('id');
if (!$adId) {
return $this->renderError('Unknown Ad');
}
$adEntity = $this->getDoctrine()->getRepository('AdBundle:AdBase')->find($adId);
if (null === $adEntity) {
return $this->renderError('Unknown Ad');
}
$reflection = new \ReflectionClass($adEntity);
$adForm = $this->getForm($reflection->getShortName());
$form = $this->createForm($adForm, $adEntity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($adEntity);
$em->flush();
return $this->redirectToRoute('ad_bundle_ad_view', array(
'id' => $adEntity->getId()
));
}
return $this->render('AdBundle:Ad:edit-ad-flat.html.twig', array(
'form' => $form->createView()
));
}
private function renderError($message = '')
{
return $this->render('::error.html.twig', array(
'error' => $message
));
}
private function getEntity($className)
{
$entityName = 'AdBundle\Entity\\' . $className;
return new $entityName();
}
private function getForm($className)
{
$formName = 'AdBundle\Form\Type\\' . $className . 'Type';
return new $formName();
}
The error message simply states that you are missing a way to set the entity's $id property. It doesn't tell you anything about the class not extending the base class. However, your base class only defines a getter method for the $id property but no setter method.
Doctrine Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly you need to work with the MappedSuperClass here is an example
When I use :
php app/console doctrine:fixtures:load --fixtures=/var/www/Symfony/src/BISSAP/ForumBundle/DataFixtures/ORM
I get :
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'INSERT INTO Post (content, date_creation, date_modif, slug, topic_id, user_id) VALUES (?, ?
, ?, ?, ?, ?)' with params ["Contenu du post!! gGasp Strategie duplication article no commentSyndrome 60", "2015-08-21 14:55:24",
"2015-08-21 14:55:24", "slug-slug", null, 34]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'topic_id' cannot be null
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'topic_id' cannot be null
Entity Post.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\PostRepository")
*/
class Post
{
/**
* #ORM\ManyToOne(targetEntity="topic", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $topic;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="Posts", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modif", type="datetime")
*/
private $dateModif;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* Constructor
*/
public function __construct()
{
$this->dateCreation = new \DateTime();
$this->dateModif = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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 dateCreation
*
* #param \DateTime $dateCreation
* #return Post
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set dateModif
*
* #param \DateTime $dateModif
* #return Post
*/
public function setDateModif($dateModif)
{
$this->dateModif = $dateModif;
return $this;
}
/**
* Get dateModif
*
* #return \DateTime
*/
public function getDateModif()
{
return $this->dateModif;
}
/**
* Set slug
*
* #param string $slug
* #return Post
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set Topic
*
* #param \BISSAP\ForumBundle\Entity\Topic $topic
* #return Post
*/
public function setTopic(\BISSAP\ForumBundle\Entity\Topic $topic)
{
$this->Topic = $topic;
return $this;
}
/**
* Get Topic
*
* #return \BISSAP\ForumBundle\Entity\Topic
*/
public function getTopic()
{
return $this->Topic;
}
/**
* Set user
*
* #param \BISSAP\ForumBundle\Entity\User $user
* #return Post
*/
public function setUser(\BISSAP\ForumBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \BISSAP\ForumBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
Entity Topic.php :
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/*use BISSAP\BodyConcept\Entity\Forum;
*/
/**
* Topic
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\TopicRepository")
*/
class Topic
{
/**
* #ORM\ManyToOne(targetEntity="Forum", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $forum;
/**
* #var ArrayCollection $Posts
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="Topic", cascade={"persist", "remove", "merge"})
*/
private $posts;
/**
* #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;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var integer
*
* #ORM\Column(name="view_count", type="integer")
*/
private $viewCount;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var integer
*
* #ORM\Column(name="reply_count", type="integer")
*/
private $replyCount;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="genre", type="string", length=255)
*/
private $genre;
/**
* #var integer
*
* #ORM\Column(name="last_post", type="integer")
*/
private $lastPost;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Topic
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user
*
* #param integer $user
* #return Topic
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUser()
{
return $this->user;
}
/**
* Set viewCount
*
* #param integer $viewCount
* #return Topic
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* Get viewCount
*
* #return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Topic
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set replyCount
*
* #param integer $replyCount
* #return Topic
*/
public function setReplyCount($replyCount)
{
$this->replyCount = $replyCount;
return $this;
}
/**
* Get replyCount
*
* #return integer
*/
public function getReplyCount()
{
return $this->replyCount;
}
/**
* Set slug
*
* #param string $slug
* #return Topic
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set genre
*
* #param string $genre
* #return Topic
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* #return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* Set lastPost
*
* #param integer $lastPost
* #return Topic
*/
public function setLastPost($lastPost)
{
$this->lastPost = $lastPost;
return $this;
}
/**
* Get lastPost
*
* #return integer
*/
public function getLastPost()
{
return $this->lastPost;
}
/**
* Set content
*
* #param string $content
* #return Topic
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set forum
*
* #param Forum $forum
* #return Topic
*/
/*public function setForum(\BISSAP\BodyConceptBundle\Entity\Forum $forum)*/
public function setForum(Forum $forum)
{
$this->forum = $forum;
return $this;
}
/**
* Get forum
*
* #return \BISSAP\BodyConceptBundle\Entity\Forum
*/
public function getForum()
{
return $this->forum;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime();
}
/**
* Add posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
* #return Topic
*/
public function addPost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
*/
public function removePost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
Fixtures : **
**LaodPost.php :
namespace BISSAP\ForumBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use BISSAP\ForumBundle\Entity\Post;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
class LoadPost extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface
{
public function load(ObjectManager $manager)
{
$data = array(
array($this->getReference('BISSAP\ForumBundle\Entity\User-0'),'Contenu du post!! gGasp Strategie duplication article no commentSyndrome 60','slug-slug',$this->getReference('BISSAP\ForumBundle\Entity\Topic-0')),
array($this->getReference('BISSAP\ForumBundle\Entity\User-0'),'Contenu du post!! gGasp Strategie duplication article no commentSyndrome 60','slug-slug',$this->getReference('BISSAP\ForumBundle\Entity\Topic-1')));
foreach ($data as $P) {
$post = new Post();
$post->setUser($P[0]);
$post->setContent($P[1]);
$post->setSlug($P[2]);
$post->setTopic($P[3]);
$manager->persist($post);
}
/*TEST OK*/
$myFile = fopen('/home/sebastien/test_topic.txt','a+');
fputs($myFile, $this->getReference('BISSAP\ForumBundle\Entity\Topic-0')->getUser()->getPseudo());
fclose($myFile);
/*END TEST*/
$manager->flush();
}
public function getOrder()
{
return 5;
}
}
LoadTopic.php:
<?php
namespace BISSAP\ForumBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use BISSAP\ForumBundle\Entity\Forum;
use BISSAP\ForumBundle\Entity\Category;
use BISSAP\ForumBundle\Entity\Topic;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
class LoadTopic extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface
{
public function load(ObjectManager $manager)
{
$data = array(
array('Perte de Volume Musculaire Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-0'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Mental Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-1'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Cosmik Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-1'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Sonor Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-2'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Sonor Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-2'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Sonor Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-2'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')),
array('Perte de Volume Strategique Inexpliqué',$this->getReference('BISSAP\ForumBundle\Entity\User-0'),'60','25','slug-slug','genre','256','Besoins d\'aide pitié...',$this->getReference('BISSAP\ForumBundle\Entity\Forum-0')));
$i=0;
foreach ($data as $Top) {
$topic = new Topic();
$topic->setTitle($Top[0]);
$topic->setUser($Top[1]);
$topic->setViewCount($Top[2]);
$topic->setReplyCount($Top[3]);
$topic->setSlug($Top[4]);
$topic->setGenre($Top[5]);
$topic->setLastPost($Top[6]);
$topic->setContent($Top[7]);
$topic->setForum($Top[8]);
$this->addReference('BISSAP\ForumBundle\Entity\Topic-'.$i,$topic);
$i++;
$manager->persist($topic);
}
$manager->flush();
}
public function getOrder()
{
return 4;
}
}
I load, LoadTopic.php in first and then LoadPost.php
In all, i have 5 fixtures (LoadCategory.php, LoadForum.php, LoadPost.php, LoadTopic.php, LoadUser.php)
Thank U.
I have two entities, Projects and Tasks with their respective repositories.
I am trying to create a function that will calculate the totalNumberOfTasks() , totalNumberOfCompletedTasks() and getPercentComplete().
totalNumberOfTasks() basically will fetch all the data related with a specific project_id from the tasks table.
totalNumberOfCompletedTasks() will query all the data relevant with specific project_id but only those marked as COMPLETED from the tasks table.
getPercentComplete() will calculate the percent based on the totalNumberOfTasks() and totalNumberOfCompletedTasks() functions and print in the view file.
I have tried doing {{ project.tasks|length }} % in Twig file which fetched only the total number of tasks relating to that specific id. How do I get total number of tasks and completed tasks, find the percentage then show it in the view file where every projects are shown?
Sorry for my english. I am just not being able to make the question more understandable.
Project entity:
<?php
namespace TaskManagerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Projects
* #ORM\Table()
* #ORM\Entity(repositoryClass="TaskManagerBundle\Entity\Repository\ProjectsRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Projects
{
/**
*
* #ORM\OneToMany(targetEntity="Tasks", mappedBy="projects")
*/
protected $tasks;
/**
* #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=30)
*/
private $title;
/**
* #var boolean
*
* #ORM\Column(name="completed", type="boolean")
*/
private $completed;
/**
* #var \Date
*
* #ORM\Column(name="due_date", type="date")
*/
private $dueDate;
/**
* #var \Date
*
* #ORM\Column(name="created", type="date")
*/
private $created;
/**
* #var \Date
*
* #ORM\Column(name="updated", type="date")
*/
private $updated;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Projects
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set completed
*
* #param boolean $completed
* #return Projects
*/
public function setCompleted($completed)
{
$this->completed = $completed;
return $this;
}
/**
* Get completed
*
* #return boolean
*/
public function getCompleted()
{
return $this->completed;
}
/**
* Set dueDate
*
* #param \Date $dueDate
* #return Projects
*/
public function setDueDate($dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* Get dueDate
*
* #return \Date
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* Set created
*
* #param \Date $created
* #return Projects
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \date
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \Date $updated
* #return Projects
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \Date
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #ORM\PrePersist
*/
public function setCreatedValue()
{
$this->created = new \DateTime();
}
/**
* #ORM\PreUpdate
*/
public function setUpdatedValue()
{
$this->updated = new \DateTime();
}
public function getNumberOfTasks()
{
}
/**
* Constructor
*/
public function __construct()
{
$this->tasks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tasks
*
* #param \TaskManagerBundle\Entity\Tasks $tasks
* #return Projects
*/
public function addTask(\TaskManagerBundle\Entity\Tasks $tasks)
{
$this->tasks[] = $tasks;
return $this;
}
/**
* Remove tasks
*
* #param \TaskManagerBundle\Entity\Tasks $tasks
*/
public function removeTask(\TaskManagerBundle\Entity\Tasks $tasks)
{
$this->tasks->removeElement($tasks);
}
/**
* Get tasks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTasks()
{
return $this->tasks;
}
}
Tasks entity:
namespace TaskManagerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Tasks
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="TaskManagerBundle\Entity\Repository\TasksRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Tasks
{
/**
*
* #ORM\ManyToOne(targetEntity="Projects", inversedBy="tasks")
* #ORM\JoinColumn(name="projects_id", referencedColumnName="id")
*/
protected $projects;
/**
* #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=30)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="date")
*/
private $updated;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="date")
*/
private $created;
/**
* #var \DateTime
*
* #ORM\Column(name="due_date", type="date")
*/
private $dueDate;
/**
* #var boolean
*
* #ORM\Column(name="completed", type="boolean")
*/
private $completed;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Tasks
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Tasks
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Tasks
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set created
*
* #param \DateTime $created
* #return Tasks
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set dueDate
*
* #param \DateTime $dueDate
* #return Tasks
*/
public function setDueDate($dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* Get dueDate
*
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* Set completed
*
* #param boolean $completed
* #return Tasks
*/
public function setCompleted($completed)
{
$this->completed = $completed;
return $this;
}
/**
* Get completed
*
* #return boolean
*/
public function getCompleted()
{
return $this->completed;
}
/**
* Set projects
*
* #param \TaskManagerBundle\Entity\Projects $projects
* #return Tasks
*/
public function setProjects(\TaskManagerBundle\Entity\Projects $projects = null)
{
$this->projects = $projects;
return $this;
}
/**
* Get projects
*
* #return \TaskManagerBundle\Entity\Projects
*/
public function getProjects()
{
return $this->projects;
}
}
Controller:
<?php
namespace TaskManagerBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use TaskManagerBundle\Entity\Projects;
use TaskManagerBundle\Form\ProjectType;
class DefaultController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('TestBundle:Projects')->findAll();
return $this->render('TestBundle:Default:index.html.twig', 'projects' => $entities]);
}
}
you can archive this problem using the Doctrine Criteria instead of make a custom Repository method. As Example you can add the following method to your Projects Entity class:
use Doctrine\Common\Collections\Criteria; // IMPORT THIS!
use Doctrine\ORM\Mapping as ORM;
/**
* Projects
* #ORM\Table()
* #ORM\Entity(repositoryClass="TaskManagerBundle\Entity\Repository\ProjectsRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Projects
{
...
public function getCompleteTasks()
{
$expr = Criteria::expr();
$criteria = Criteria::create();
$criteria->where($expr->eq('completed', true));
return $this->getTasks()->matching($criteria);
}
public function getNumberOfTasks()
{
return $this->getTasks()->count();
}
public function getPercentComplete()
{
$percentage = 0;
$totalSize = $this->getNumberOfTasks();
if ($totalSize>0)
{
$completedSize = $this->getCompleteTasks()->count();
$percentage = $completedSize / $totalSize * 100;
}
return $percentage;
}
...
}
Then you can use in your Twig template as follow:
{{ project.percentComplete|number_format(2, '.', ',') }}
Hope this help.
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.
I have following entity class and controller class. I have exposed selected properties.
In my "getAlbumsAction()" the output is the way i want.
But in "getAlbumAction($id)" i want to expose all the properties of the album class. How can i achive it? Have been searching around for a while but can't get it.
<?php
namespace MyBundle\RestApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
/**
* Album
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\RestApiBundle\Entity\AlbumRepository")
* #ExclusionPolicy("all")
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #expose
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #expose
*/
private $name;
/**
*
* #ORM\OneToMany(targetEntity="Track", mappedBy="album")
*
*/
private $tracks;
/**
*
* #ORM\Column(name="likes", type="integer")
*
*
*/
private $likes;
/**
* #var \DateTime
*
* #ORM\Column(name="released", type="date")
*
*
*/
private $released;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="date")
*/
private $updated;
/**
* #ORM\ManyToOne(targetEntity="Language", inversedBy="albums")
* #ORM\JoinColumn(name="language_id", referencedColumnName="id")
*
*
*/
private $language;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Album
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set released
*
* #param \DateTime $released
* #return Album
*/
public function setReleased($released)
{
$this->released = $released;
return $this;
}
/**
* Get released
*
* #return \DateTime
*/
public function getReleased()
{
return $this->released;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Album
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set language
*
* #param integer $language
* #return Album
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* #return integer
*/
public function getLanguage()
{
return $this->language;
}
/**
* Constructor
*/
public function __construct()
{
$this->tracks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
* #return Album
*/
public function addTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks[] = $tracks;
return $this;
}
/**
* Remove tracks
*
* #param \MyBundle\RestApiBundle\Entity\Track $tracks
*/
public function removeTrack(\MyBundle\RestApiBundle\Entity\Track $tracks)
{
$this->tracks->removeElement($tracks);
}
/**
* Get tracks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTracks()
{
return $this->tracks;
}
/**
* Set likes
*
* #param integer $likes
* #return Album
*/
public function setLikes($likes)
{
$this->likes = $likes;
return $this;
}
/**
* Get likes
*
* #return integer
*/
public function getLikes()
{
return $this->likes;
}
}
<?php
namespace MyBundle\RestApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
class AlbumController extends Controller {
public function getAlbumsAction() {
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyBundleRestApiBundle:Album')->findAll();
return array(
'albums' => $entities,
);
}
private function getEntity($id) {
$entityName = 'MyBundleRestApiBundle:Album';
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository($entityName)->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find organisation entity');
}
return $entity;
}
public function getAlbumAction($id) {
$entity = $this->getEntity($id);
return array(
'album' => $entity,
);
}
}
you have a typo:
'album' => $entities but must be 'album' => $entity
also if you want to return different fields/formats for one object check this out
http://jmsyst.com/libs/serializer/master/reference/annotations#groups