Doctrine Query builder, count related one to many rows - php

<?php
namespace Raltech\WarehouseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="warehouse_magazine")
*/
class Magazine
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\OneToMany(targetEntity="Wardrobe", mappedBy="magazine",cascade={"remove"})
*/
protected $wardrobe;
public function __construct()
{
$this->wardrobe = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Magazine
*/
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 Magazine
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Add wardrobe
*
* #param \Raltech\WarehouseBundle\Entity\Wardrobe $wardrobe
* #return Magazine
*/
public function addWardrobe(\Raltech\WarehouseBundle\Entity\Wardrobe $wardrobe)
{
$this->wardrobe[] = $wardrobe;
return $this;
}
/**
* Remove wardrobe
*
* #param \Raltech\WarehouseBundle\Entity\Wardrobe $wardrobe
*/
public function removeWardrobe(\Raltech\WarehouseBundle\Entity\Wardrobe $wardrobe)
{
$this->wardrobe->removeElement($wardrobe);
}
/**
* Get wardrobe
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getWardrobe()
{
return $this->wardrobe;
}
}
<?php
namespace Raltech\WarehouseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="warehouse_wardrobe")
*/
class Wardrobe
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="text")
*/
protected $description;
/**
* #ORM\ManyToOne(targetEntity="Magazine", inversedBy="wardrobe")
* #ORM\JoinColumn(name="magazine_id", referencedColumnName="id")
*/
protected $magazine;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Wardrobe
*/
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 Wardrobe
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set magazine
*
* #param \Raltech\WarehouseBundle\Entity\Magazine $magazine
* #return Wardrobe
*/
public function setMagazine(\Raltech\WarehouseBundle\Entity\Magazine $magazine = null)
{
$this->magazine = $magazine;
return $this;
}
/**
* Get magazine
*
* #return \Raltech\WarehouseBundle\Entity\Magazine
*/
public function getMagazine()
{
return $this->magazine;
}
}
My 2 entites, i want count how many Wardrobes is related for each magazines, i must make this from querybuilder
$em = $this->get('doctrine.orm.entity_manager');
$userRepository = $em->getRepository('Raltech\WarehouseBundle\Entity\Magazine');
$qb = $userRepository->createQueryBuilder('magazine')
->addSelect("magazine.id,magazine.name,magazine.description")
->InnerJoin('magazine.wardrobe', 'wardrobe')
->addSelect('COUNT(wardrobe.id) AS wardrobecount')
This didn't work of course.
So, somebody can me provide example how to count this from querybuilder?

Summarising the comments:
$qb = $userRepository->createQueryBuilder('magazine')
->addSelect("magazine.id,magazine.name,magazine.description")
->leftJoin('magazine.wardrobe', 'wardrobe') // To show as well the magazines without wardrobes related
->addSelect('COUNT(wardrobe.id) AS wardrobecount')
->groupBy('magazine.id'); // To group the results per magazine

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).

Cannot get related entity field to save in Symfony Admin Form

I'm working my way through Symfony trying to learn how it all fits together and I'm working on the admin section.
Right now I'm putting together an admin form for a Show Entity which will reference a section entity (so this show belongs in that section, etc). Every other field in the form saves EXCEPT for the related entity choice field.
This is the ShowAdmin class
<?php
namespace AppBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Nelmio\ApiDocBundle\Tests\Fixtures\Form\EntityType;
class ShowAdmin extends AbstractAdmin {
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('title', 'text')
->add('shortname', 'text')
->add('section_id', EntityType::class, array(
'class' => 'AppBundle:SectionEntity',
'choice_label' => 'section_title',
))
->add('logo', 'text')
->add('description', 'textarea')
->add('status', 'integer');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper->add('title');
$datagridMapper->add('shortname');
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper->addIdentifier('title');
$listMapper->add('shortname', 'text');
}
}
This is the ShowEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="shows")
*/
class ShowEntity {
function __construct() {
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $title;
/**
* #ORM\Column(type="string", length=100)
*/
private $shortname;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SectionEntity")
*/
private $section;
/**
* #ORM\Column(type="string", length=255)
*/
private $logo;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="integer")
*/
private $status;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return ShowEntity
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set sectionId
*
* #param integer $sectionId
*
* #return ShowEntity
*/
public function setSectionId($sectionId)
{
$this->section_id = $sectionId;
return $this;
}
/**
* Get sectionId
*
* #return integer
*/
public function getSectionId()
{
return $this->section_id;
}
/**
* Set logo
*
* #param string $logo
*
* #return ShowEntity
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* #return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set description
*
* #param string $description
*
* #return ShowEntity
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set status
*
* #param integer $status
*
* #return ShowEntity
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set shortname
*
* #param string $shortname
*
* #return ShowEntity
*/
public function setShortname($shortname)
{
$this->shortname = $shortname;
return $this;
}
/**
* Get shortname
*
* #return string
*/
public function getShortname()
{
return $this->shortname;
}
}
And this is the SectionEntity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SectionEntity
*
* #ORM\Table(name="section_entity")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SectionEntityRepository")
*/
class SectionEntity
{
protected $section_id;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $section_title;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set sectionTitle
*
* #param string $sectionTitle
*
* #return SectionEntity
*/
public function setSectionTitle($sectionTitle)
{
$this->section_title = $sectionTitle;
return $this;
}
/**
* Get sectionTitle
*
* #return string
*/
public function getSectionTitle()
{
return $this->section_title;
}
/**
* Get string
*/
public function __toString() {
return $this->section_title;
}
function __construct() {
$this->section_id = new \Doctrine\Common\Collections\ArrayCollection();
}
}
Any help would be greatly appreciated, I know it's probably something super simple that I'm just not seeing.
Thanks.
(optional) Rename ShowEntity::$section into ShowEntity::$sections to highlight sections is a collection but not a single entity.
Set ShowEntity __construct method body to:
$this->sections = new \Doctrine\Common\Collections\ArrayCollection();
At ShowAdmin::configureFormFields rename
->add('section_id', EntityType::class, array(
into
->add('section', EntityType::class, array(
You should use direct reference to the relation instead of id.
Remove SectionEntity::__construct method, it has no sense.
Remove protected $section_id; from SectionEntity.
Change public function setSectionId($sectionId) into public function setSection(Section $section).
Perhaps you also need to rename section_title into sectionTitle or simply title, not sure about that.

Symfony One-To-One Unidirectional relationship How can I make Doctrine create a new Menu if a new Coffeeshop is made?

I have a bit of a problem figuring out the following:
How can I make Symfony insert a new menu when a new coffeeshop has been made with a form? (foreign key in menu is shopid)
Thanks in advance, code below.
Menu Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Menu
*
* #ORM\Table(name="menu")
* #ORM\Entity(repositoryClass="AppBundle\Repository\MenuRepository")
*
*/
class Menu
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="Coffeeshop")
* #ORM\JoinColumn(name="coffeeshop_id", referencedColumnName="id")
*/
private $shopId;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set shopId
*
* #param integer $shopId
*
* #return Menu
*/
public function setShopId($shopId)
{
$this->shopId = $shopId;
return $this;
}
/**
* Get shopId
*
* #return int
*/
public function getShopId()
{
return $this->shopId;
}
/**
* Set lastUpdated
*
* #param \DateTime $lastUpdated
*
* #return Menu
*/
public function setLastUpdated($lastUpdated)
{
$this->lastUpdated = $lastUpdated;
return $this;
}
/**
* Get lastUpdated
*
* #return \DateTime
*/
public function getLastUpdated()
{
return $this->lastUpdated;
}
/**
* Set updated
*
* #param \DateTime $updated
*
* #return Menu
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
}
Coffeeshop Entity:
<?php
/// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="coffeeshop")
*/
class Coffeeshop
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $name;
/**
* #ORM\Column(type="string")
*/
private $phone;
/**
* #ORM\Column(type="string", length=50)
*/
private $streetName;
/**
* #ORM\Column(type="string", length=6)
*/
private $houseNumber;
/**
* #ORM\Column(type="string", length=7)
*/
private $zipcode;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Coffeeshop
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set phone
*
* #param string $phone
*
* #return Coffeeshop
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Set streetName
*
* #param string $streetName
*
* #return Coffeeshop
*/
public function setStreetName($streetName)
{
$this->streetName = $streetName;
return $this;
}
/**
* Get streetName
*
* #return string
*/
public function getStreetName()
{
return $this->streetName;
}
/**
* Set houseNumber
*
* #param string $houseNumber
*
* #return Coffeeshop
*/
public function setHouseNumber($houseNumber)
{
$this->houseNumber = $houseNumber;
return $this;
}
/**
* Get houseNumber
*
* #return string
*/
public function getHouseNumber()
{
return $this->houseNumber;
}
/**
* Set description
*
* #param string $description
*
* #return Coffeeshop
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set zipcode
*
* #param string $zipcode
*
* #return Coffeeshop
*/
public function setZipcode($zipcode)
{
$this->zipcode = $zipcode;
return $this;
}
/**
* Get zipcode
*
* #return string
*/
public function getZipcode()
{
return $this->zipcode;
}
/**
* Set menu
*
* #param \AppBundle\Entity\Menu $menu
*
* #return Coffeeshop
*/
public function setMenu(\AppBundle\Entity\Menu $menu = null)
{
$this->menu = $menu;
return $this;
}
/**
* Get menu
*
* #return \AppBundle\Entity\Menu
*/
public function getMenu()
{
return $this->menu;
}
/**
* Set coffeeshopmenu
*
* #param \AppBundle\Entity\Menu $coffeeshopmenu
*
* #return Coffeeshop
*/
public function setCoffeeshopmenu(\AppBundle\Entity\Menu $coffeeshopmenu = null)
{
$this->coffeeshopmenu = $coffeeshopmenu;
return $this;
}
/**
* Get coffeeshopmenu
*
* #return \AppBundle\Entity\Menu
*/
public function getCoffeeshopmenu()
{
return $this->coffeeshopmenu;
}
}
Coffeeshop FormBuilder:
<?php
/**
* Created by PhpStorm.
* User:
* Date: 23-9-2016
* Time: 14:20
*/
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class CoffeeshopType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('phone')
->add('streetName')
->add('houseNumber')
->add('zipcode')
->add('description')
->add('save', SubmitType::class, array('label' => 'Add shop'))
;
}
}
In many ways:
you can define Coffeeshoptypeas a service, then inject ManagerRegistry (#doctrine) to __construct() (or just EntityManager), set an event listener for event FormEvents::POST_SUBMIT. Something like that:
$this->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) {/*...*/});
in controller, where you persist changes from Coffeeshoptype
use an event listener for Doctrine (or create an entity listener, feature from Doctrine). With doctrine events, you can find if entity (Coffeeshop) is persisting or updating and depends of situation, create new menu.
All of above methods can have access to Doctrine (thanks to Dependency Injection), also some of these methods are bad approaches. I suggest to attach EventListener (or EventSubscriber) to one of Doctrine Events and then do persisting for new menu. But if you need to create a new menu only when Coffeeshop is submitted by form, create event listener in form type.

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.

Symfony 2 computer hungs when I make any request

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)

Categories