Doctrine 2.2.2 - issue inserting multiple entries at once? - php

I am unable to get this to work correctly.
It will insert entries twice and never set the project_id in project_data table, its always 0.
I have tried inserting multiple ways..
Like so
//... do some work
$project = new PSD_Model_Entity_Project();
$project->setStatusId($this->_em->find("PSD_Model_Entity_Status", '3'));
$project->addData('hello', $data->data->hello);
$this->_em->persist($project);
$this->_em->flush();
And Like so
$project = new PSD_Model_Entity_Project();
$project->setStatusId($this->_em->find("PSD_Model_Entity_Status", '3'));
$project_data = new PSD_Model_Entity_Project_Data('hello', $data->data->hello,$project);
$this->_em->persist($project);
$this->_em->persist($project_data);
$this->_em->flush();
Doctrine Model:
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* PSD_Model_Entity_Project
* #Entity
* #Table(name="project")
*/
class PSD_Model_Entity_Project
{
/**
* #var integer $project_id
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
private $project_id;
/**
* #var integer $dependent
* #Column(type="integer")
*/
private $dependent;
/**
* #var integer $iduser
* #Column(type="integer")
*/
private $iduser;
/**
* #var datetime $created
* #Column(type="datetime")
*/
private $created;
/**
* #var datetime $modified
* #Column(type="datetime")
*/
private $modified;
/**
* #var PSD_Model_Entity_Status
* #ManyToOne(targetEntity="PSD_Model_Entity_Status")
* #JoinColumn(name="status_id", referencedColumnName="status_id")
*/
private $status_id;
/**
* #OneToMany(targetEntity="PSD_Model_Entity_Project_Data", mappedBy="project_id", cascade={"ALL"}, indexBy="name")
*/
private $data;
public function __construct()
{
$this->data = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addData($name, $value)
{
$this->data[$name] = new PSD_Model_Entity_Project_Data($name, $value, $this);
}
/**
* Get project_id
*
* #return integer
*/
public function getProjectId()
{
return $this->project_id;
}
/**
* Set dependent
*
* #param integer $dependent
* #return PSD_Model_Entity_Project
*/
public function setDependent($dependent)
{
$this->dependent = $dependent;
return $this;
}
/**
* Get dependent
*
* #return integer
*/
public function getDependent()
{
return $this->dependent;
}
/**
* Set iduser
*
* #param integer $iduser
* #return PSD_Model_Entity_Project
*/
public function setIduser($iduser)
{
$this->iduser = $iduser;
return $this;
}
/**
* Get iduser
*
* #return integer
*/
public function getIduser()
{
return $this->iduser;
}
/**
* Set created
*
* #param datetime $created
* #return PSD_Model_Entity_Project
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return datetime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set modified
*
* #param datetime $modified
* #return PSD_Model_Entity_Project
*/
public function setModified($modified)
{
$this->modified = $modified;
return $this;
}
/**
* Get modified
*
* #return datetime
*/
public function getModified()
{
return $this->modified;
}
/**
* Set status_id
*
* #param PSD_Model_Entity_Status $statusId
* #return PSD_Model_Entity_Project
*/
public function setStatusId(\PSD_Model_Entity_Status $statusId = null)
{
$this->status_id = $statusId;
return $this;
}
/**
* Get status_id
*
* #return PSD_Model_Entity_Status
*/
public function getStatusId()
{
return $this->status_id;
}
}
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* PSD_Model_Entity_Project_Data
* #Entity
* #Table(name="project_data")
*/
class PSD_Model_Entity_Project_Data
{
/**
* #var integer $project_data_id
* #Id #Column(type="integer")
* #GeneratedValue(strategy="AUTO")
*/
private $project_data_id;
/**
* #var integer $project_id
* #Column(type="integer")
* #ManyToOne(targetEntity="PSD_Model_Entity_Project", inversedBy="data")
*/
private $project_id;
/**
* #var string $name
* #Column(type="string")
*/
private $name;
/**
* #var string $value
* #Column(type="string")
*/
private $value;
public function __construct($name, $value, $project)
{
$this->name = $name;
$this->value = $value;
$this->project_id = $project;
}
/**
* Set project_id
*
* #param PSD_Model_Entity_Project $projectId
* #return PSD_Model_Entity_Project_Data
*/
public function setProjectId(\PSD_Model_Entity_Project $projectId = null)
{
$this->project_id = $projectId;
return $this;
}
/**
* Get project_id
*
* #return integer
*/
public function getProjectId()
{
return $this->project_id;
}
/**
* Set name
*
* #param string $name
* #return PSD_Model_Entity_Project_Data
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set value
*
* #param string $value
* #return PSD_Model_Entity_Project_Data
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return $this->value;
}
}

I believe your data model properties should be marked as protected instead of private, according to the docs.
The reference to $project_id inside your PSD_Model_Entity_Project_Data currently has this:
/**
* #Column(type="integer")
* #ManyToOne(targetEntity="PSD_Model_Entity_Project", inversedBy="data")
*/
You could try changing the Column to JoinColumn:
/**
* #JoinColumn()
* #ManyToOne(targetEntity="PSD_Model_Entity_Project", inversedBy="data")
*/
Btw, I have a similar model and didn't need the inversedBy; but it's been a while since I have touched Doctrine so this may not make any difference whatsoever :)

Try this. Try setting the attributes, via the set, not with the constructor and see if this eliminates the duplicate row.

Related

Symfony 3.3 Schema Validation Error

I have two entities as follows:
<?php
// src/coreBundle/Entity/model.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\brand;
/**
*#ORM\Entity
*#ORM\Table(name="model")
*/
class model
{
/**
* #ORM\ManyToOne(targetEntity="coreBundle\Entity\brand", inversedBy="models")
* #ORM\JoinColumn(name="brand_id", referencedColumnName="id")
*/
private $brands;
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
*#ORM\Column(type="integer")
*/
public $brand_id;
/**
*#ORM\Column(type="string", length=100)
*/
private $name;
/**
*#ORM\Column(type="string", length=100)
*/
private $image_url;
/**
*#ORM\Column(type="string", length=200)
*/
private $comment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set brandId
*
* #param integer $brandId
*
* #return model
*/
public function setBrandId($brandId)
{
$this->brand_id = $brandId;
return $this;
}
/**
* Get brandId
*
* #return integer
*/
public function getBrandId()
{
return $this->brand_id;
}
/**
* Set name
*
* #param string $name
*
* #return model
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set imageUrl
*
* #param string $imageUrl
*
* #return model
*/
public function setImageUrl($imageUrl)
{
$this->image_url = $imageUrl;
return $this;
}
/**
* Get imageUrl
*
* #return string
*/
public function getImageUrl()
{
return $this->image_url;
}
/**
* Set comment
*
* #param string $comment
*
* #return model
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set brands
*
* #param \coreBundle\Entity\brand $brands
*
* #return model
*/
public function setBrands(\coreBundle\Entity\brand $brands = null)
{
$this->brands = $brands;
return $this;
}
/**
* Get brands
*
* #return \coreBundle\Entity\brand
*/
public function getBrands()
{
return $this->brands;
}
}
And Second one is as follows:
<?php
// src/coreBundle/Entity/brand.php
namespace coreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use coreBundle\Entity\model;
use Doctrine\Common\Collections\ArrayCollection;
/**
*#ORM\Entity
*#ORM\Table(name="brand")
*/
class brand
{
/**
* ORM\OneToMany(targetEntity="coreBundle\Entity\model", mappedBy="brands")
*/
private $models;
public function __construct()
{
$this->models = new ArrayCollection();
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
*#ORM\Column(type="string", length=100)
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return brand
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
"model" has a ManyToOne relationship with "brand"
I am having issues of schema validation,
*The association coreBundle\Entity\model#brands refers to the inverse side field coreBundle\Entity\brand#models which does not exist
Can you tell what am I doing wrong, Thanks in advance.
In case your still wondering after 3 hours of agony, your missing the # in #ORM\OneToMany (brand.php).

Symfony Doctrine entity relations returns null data on saving

I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;

Symfony2 After form submit entity not extended on base entity

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

Calculate percentage in Symfony2

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.

Symfony2 FosRestBundle Expose Properties at runtime

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

Categories