Doctrine form generation throws Twig error - php

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)

Related

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.

Doctrine Scheme update. Overlooking entities

I have created 2 new entities and when I run
app/console doctrine:schema:update --force
It says i am up to date and these two new entities do not get tables created.
Every other command i have found will detect entities in other bundles but none from the bundle i am working on. Example would be
app/console doctrine:mapping:info
It does not show there either.
Here is a example of one. This lives in the Entity Folder of my bundle
<?php
namespace test\OrganizationBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Department
* #ORM\Entity
* #ORM\Table(name="departments")
*/
class Department
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=false)
*/
private $name;
/**
* #var integer
* #ORM\Column(name="facilityId", type="int")
*
*/
private $facilityId;
/**
* #var \DateTime
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #var \DateTime
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var array
* #ORM\ManyToMany(targetEntity="DeptTag", mappedBy="departments")
*/
private $deptTags;
public function __construct()
{
$this->deptTags = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Department
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set facilityId
*
* #param string $facilityId
*
* #return Department
*/
public function setFacilityId($facilityId)
{
$this->facilityId = $facilityId;
return $this;
}
/**
* Get facilityId
*
* #return string
*/
public function getFacilityId()
{
return $this->facilityId;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Department
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \DateTime $updated
*
* #return Department
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set deptTags
*
* #param array $deptTags
*
* #return Department
*/
public function setDeptTags($deptTags)
{
$this->deptTags = $deptTags;
return $this;
}
/**
* Get deptTags
*
* #return array
*/
public function getDeptTags(DeptTag)
{
return $this->deptTags[] = $deptTag;
}
}

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.

How to use getQuery()->getOneOrNullresult() return

in my test project I have 2 entities :
- endUser (extend of FOSUserBundle)
- Rezo (will containt approved relation between two members)
the both entities have been defined as :
EndUser Entity :
<?php
namespace Core\CustomerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* EndUser
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
*/
class EndUser extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* #var string
* #ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaissance", type="datetime", nullable=true)
*/
private $DateNaissance;
/**
* #ORM\OneToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"persist", "merge", "remove"})
* #ORM\JoinColumn(name="adressbook_id", referencedColumnName="id", nullable=true)
*/
private $adressbook;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Discipline", mappedBy="endusers")
*/
private $disciplines;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Experiences", mappedBy="endusers")
*/
private $experiences;
/**
* #var string
* #ORM\Column(name="avatar", type="string", length=255, nullable=true)
*/
private $avatar;
/**
* #var string
* #ORM\Column(name="repository", type="string", length=255, nullable=true)
*/
private $repository;
/**
* #ORM\OneToMany(targetEntity="Core\MyEquiBookBundle\Entity\NiveauEndUser", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $niveaux;
/**
* #ORM\OneToMany(targetEntity="Core\GeneralBundle\Entity\Rezo", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $friends;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->disciplines = new \Doctrine\Common\Collections\ArrayCollection();
$this->niveaux = new \Doctrine\Common\Collections\ArrayCollection();
$this->experiences = new \Doctrine\Common\Collections\ArrayCollection();
$this->friends = new \Doctrine\Common\Collections\ArrayCollection();
$this->expiresAt = new \DateTime("+1 year");
$this->credentialsExpireAt = new \DateTime("+1 year");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set avatar
*
* #param string $avatar
* #return EndUser
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set repository
*
* #param string $repository
* #return EndUser
*/
public function setRepository($repository)
{
$this->repository = $repository;
return $this;
}
/**
* Get repository
*
* #return string
*/
public function getRepository()
{
return $this->repository;
}
/**
* Set adressbook
*
* #param \Core\CustomerBundle\Entity\EndUser $adressbook
* #return EndUser
*/
public function setAdressbook(\Core\CustomerBundle\Entity\EndUser $adressbook = null)
{
$this->adressbook = $adressbook;
return $this;
}
/**
* Get adressbook
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getAdressbook()
{
return $this->adressbook;
}
/**
* Add disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
* #return EndUser
*/
public function addDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines[] = $disciplines;
return $this;
}
/**
* Remove disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
*/
public function removeDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines->removeElement($disciplines);
}
/**
* Get disciplines
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDisciplines()
{
return $this->disciplines;
}
/**
* Add niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
* #return EndUser
*/
public function addNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux[] = $niveaux;
return $this;
}
/**
* Remove niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
*/
public function removeNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux->removeElement($niveaux);
}
/**
* Get niveaux
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNiveaux()
{
return $this->niveaux;
}
/**
* Add experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
* #return EndUser
*/
public function addExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences[] = $experiences;
return $this;
}
/**
* Remove experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
*/
public function removeExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences->removeElement($experiences);
}
/**
* Get experiences
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getExperiences()
{
return $this->experiences;
}
/**
* Add friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
* #return EndUser
*/
public function addFriend(\Core\GeneralBundle\Entity\Rezo $friends )
{
$this->friends[] = $friends;
return $this;
}
/**
* Remove friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
*/
public function removeFriend(\Core\GeneralBundle\Entity\Rezo $friends)
{
$this->friends->removeElement($friends);
}
/**
* Get friends
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFriends()
{
return $this->friends;
}
/**
* Set firstname
*
* #param string $firstname
* #return EndUser
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return EndUser
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set DateNaissance
*
* #param \DateTime $dateNaissance
* #return EndUser
*/
public function setDateNaissance($dateNaissance)
{
$this->DateNaissance = $dateNaissance;
return $this;
}
/**
* Get DateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->DateNaissance;
}
}
Rezo Entity :
<?php
namespace Core\GeneralBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Rezo
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\GeneralBundle\Entity\RezoRepository")
*/
class Rezo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="RequestedDate", type="datetime")
*/
private $requestedDate;
/**
* #var \DateTime
*
* #ORM\Column(name="AcceptedDate", type="datetime", nullable=true)
*/
private $acceptedDate;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\Enduser", inversedBy="friends", cascade={"refresh"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $enduser;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"refresh"})
* #ORM\JoinColumn(name="friendwith", referencedColumnName="id")
*/
protected $friendwith;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set requestedDate
*
* #param \DateTime $requestedDate
* #return Rezo
*/
public function setRequestedDate($requestedDate)
{
$this->requestedDate = $requestedDate;
return $this;
}
/**
* Get requestedDate
*
* #return \DateTime
*/
public function getRequestedDate()
{
return $this->requestedDate;
}
/**
* Set acceptedDate
*
* #param \DateTime $acceptedDate
* #return Rezo
*/
public function setAcceptedDate($acceptedDate)
{
$this->acceptedDate = $acceptedDate;
return $this;
}
/**
* Get acceptedDate
*
* #return \DateTime
*/
public function getAcceptedDate()
{
return $this->acceptedDate;
}
/**
* Set enduser
*
* #param \Core\CustomerBundle\Entity\EndUser $enduser
* #return Rezo
*/
public function setEnduser(\Core\CustomerBundle\Entity\EndUser $enduser = null)
{
$this->enduser = $enduser;
return $this;
}
/**
* Get enduser
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getEnduser()
{
return $this->enduser;
}
/**
* Set friendwith
*
* #param \Core\CustomerBundle\Entity\EndUser $friendwith
* #return Rezo
*/
public function setFriendwith(\Core\CustomerBundle\Entity\EndUser $friendwith = null)
{
$this->friendwith = $friendwith;
return $this;
}
/**
* Get friendwith
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getFriendwith()
{
return $this->friendwith;
}
when I run :
app/console doctrine:schema:update --force
The following MySQL table has been created :
CREATE TABLE IF NOT EXISTS `Rezo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`friendwith` int(11) DEFAULT NULL,
`RequestedDate` datetime NOT NULL,
`AcceptedDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_681FC4BA76ED395` (`user_id`),
KEY `IDX_681FC4B1094AD75` (`friendwith`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
In the RezoController.php controller I would like to give to endUser opportunity to accept a contact request fot this I have created a function named : acceptnewrequestAction($id)
public function acceptnewrequestAction($id){
$em = $this->getDoctrine()->getManager();
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->find($id);
$user1 = $rezo->getEnduser();
$user2 = $rezo->getFriendwith();
$dateRequest = $rezo->getRequestedDate();
$rezo->setAcceptedDate(new \DateTime('now'));
$em->persist($rezo);
$em->flush();
/* check if inverse relation exist */
$query = $em->CreateQuerybuilder();
$query->select('t0.id');
$query->from('CoreGeneralBundle:Rezo','t0');
$query->where('t0.acceptedDate IS NULL');
$query->andWhere('t0.enduser = :userId');
$query->andWhere('t0.friendwith =:userId2');
$query->SetParameters(array('userId'=> $user2, 'userId2'=>$user1));
$result = $query->getQuery()->getOneOrNullResult();
if ( is_object($result))
{
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->findById($result->getId());
$rezo->setAcceptedDate(new \DateTime('now'));
} else {
$rezo = new Rezo();
$rezo->setRequestedDate(new \Datetime('now'));
$rezo->setAcceptedDate(new \DateTime('now'));
$rezo->Setenduser($user2);
$rezo->setFriendwith($user1);
}
$em->persist($rezo);
$em->flush();
return $this->render(controller('CoreGeneralBundle:Rezo:RezoList'));
}
I would like to know how I can use results to know if one object if found or return is Null and in case it exists update it or create a new one.
thank you for your help
getOneOrNullResult method tells you if any record in database is found, or not.
If it return null, it means that you have some results, and in your case you have to insert new one.
But when it exists some records, this method will return object instance of your entity. That means in your case you have to update existing record.
Please remember, that getOneOrNullResult method throws exception, when result set is not unique.

Symfony2 - Doctrine exception: class used in the discriminator map does not exist

I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.

Categories