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.
Related
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;
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
I have a class that have relationships with other classes in my Bundle, and whenever I try to generate a form with the Doctrine command in Symfony, it fails by returning a Twig error
Key "school" for array with keys "id, startDate, endDate" does not exists in "form/formType.php.twig" at line 29
Here is my code:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Classroom
*
* #ORM\Table(name="classroom")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
*/
class Classroom
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\School", inversedBy="classrooms")
* #ORM\JoinColumn(nullable=false)
*/
private $school;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Student", mappedBy="classroom")
* #ORM\JoinColumn(nullable=false)
*/
private $students;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Teacher")
* #ORM\JoinColumn(nullable=false)
*/
private $teachers;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="date")
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="date")
*/
private $endDate;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set startDate
*
* #param \DateTime $startDate
*
* #return Classroom
*/
public function setStartDate($startDate)
{
$this->startDate = $startDate;
return $this;
}
/**
* Get startDate
*
* #return \DateTime
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* Set endDate
*
* #param \DateTime $endDate
*
* #return Classroom
*/
public function setEndDate($endDate)
{
$this->endDate = $endDate;
return $this;
}
/**
* Get endDate
*
* #return \DateTime
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* Set school
*
* #param \AppBundle\Entity\School $school
*
* #return Classroom
*/
public function setSchool(\AppBundle\Entity\School $school)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* #return \AppBundle\Entity\School
*/
public function getSchool()
{
return $this->school;
}
/**
* Constructor
*/
public function __construct()
{
$this->students = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add student
*
* #param \AppBundle\Entity\Student $student
*
* #return Classroom
*/
public function addStudent(\AppBundle\Entity\Student $student)
{
$this->students[] = $student;
return $this;
}
/**
* Remove student
*
* #param \AppBundle\Entity\Student $student
*/
public function removeStudent(\AppBundle\Entity\Student $student)
{
$this->students->removeElement($student);
}
/**
* Get students
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStudents()
{
return $this->students;
}
/**
* Add teacher
*
* #param \AppBundle\Entity\Teacher $teacher
*
* #return Classroom
*/
public function addTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers[] = $teacher;
return $this;
}
/**
* Remove teacher
*
* #param \AppBundle\Entity\Teacher $teacher
*/
public function removeTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers->removeElement($teacher);
}
/**
* Get teachers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTeachers()
{
return $this->teachers;
}
}
Do I need to add anything for it to works ? Is it because of the relationships with another class ?
Hope you can help me
As you didn't mention your Symfony version, it seems to me that you are having the same error as here:
Generating forms with Symfony 2.8 throws a Twig_Error_Runtime
Please check the solutions there
(Sorry for putting this in an answer, I don't have the reputation to comment in your question)
Excuse me for my English.
I have 3 classes: User, Category and Service.
When I do even a simple query to the database for Service, for example findAll(), my computer hangs... At the same time, the query for Category and User are good.
Thank you for your help!
User.php
namespace General\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your type.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max="255",
* minMessage="The type is too short.",
* maxMessage="The type is too long.",
* groups={"Registration", "Profile"}
* )
*/
protected $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
}
Category.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Category
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\OneToMany(targetEntity="\General\AnnuaireBundle\Entity\Service", mappedBy="categories")
*/
private $services;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
$this->services = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Category
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* #ORM\PrePersist()
*/
public function setCreatedAt($createdAt = null) {
$this->createdAt = null === $createdAt ? new \DateTime() : $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add services
*
* #param \General\AnnuaireBundle\Entity\Service $services
* #return Category
*/
public function addService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services[] = $services;
return $this;
}
/**
* Remove services
*
* #param \General\AnnuaireBundle\Entity\Service $services
*/
public function removeService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services->removeElement($services);
}
/**
* Get services
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServices()
{
return $this->services;
}
}
Service.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\ServiceRepository")
*/
class Service
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToOne(targetEntity="\General\AnnuaireBundle\Entity\Category", inversedBy="services")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $categories;
/**
* #ORM\ManyToOne(targetEntity="\General\UserBundle\Entity\User")
*/
private $users;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Service
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Service
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Service
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Service
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set categories
*
* #param \General\AnnuaireBundle\Entity\Category $categories
* #return Service
*/
public function setCategories(\General\AnnuaireBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return \General\AnnuaireBundle\Entity\Category
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set users
*
* #param \General\UserBundle\Entity\User $users
* #return Service
*/
public function setUsers(\General\UserBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* #return \General\UserBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
}
Controller.php
public function showServicesAction()
{
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services,
)
);
}
If I modified my function as:
$user = $this->container->get('security.context')->getToken()->getUser();
$user_id = $user->getId();
// var_dump($user_id); ALL IS RIGHT
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
// var_dump($user_id); ALL IS RIGHT
// IF: var_dump($services[0]); COMPUTER HUNGS
// IF: echo count($services); RESPONSE RIGHT
// IF:
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services, ));
// SCREEN WHITE
If you print object in browser it get hanged because symphony object contains lots of info. suppose if you have relation with other tables it will have current tables info as well as other related tables info (Schema, Data, Relationship etc.) as well so it might 99% chance to hanged the browser. Better to print "echo count($services)" to check object exists or not.
Try Debug::dump($service) or any variable - you will be able to see the objects (without the proxy)
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