Entity was not found - php

I am having troubles with only 1 class in symfony2,
Every time i try to use the entity in a template it says the entity was not found.
However everything works perfectly fine on localhost (both dev and prod environment work), but it all stops working when i deploy it on the remote webserver.
I restarted httpd already and tried different methods.
The Entity UserApplication has an association on the Application entity, i am trying to get the name from the application trough the UserApplication in my template file
This is the error message i is throwing,
[ERROR]: An exception has been thrown during the rendering of a
template ("Entity was not found.") in
"MyBundle:Application:applications_user.html.twig" at line 34. with
code: 0 (file: mylocation/20131209193528/app/cache/prod/classes.php,
line: 4485)
Snippet: applications_user.html.twig
{% extends 'MaximCMSBundle:Default:index.html.twig' %}
{% block body %}
<div class="page">
<h3 class="page-header">Applications</h3>
<div class="page-content">
<ul class="menu menu-clean">
{% for application in applications %}
<li>
<span>{{ application.application.name }}</span>
</li>
{% else %}
<p>There are no open applications at the moment</p>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
Entity UserApplication
<?php
namespace MyName\Module\ApplicationBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* UserApplication
*
* #ORM\Table(name="user_application")
* #ORM\Entity
*/
class UserApplication {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var User
*
* #ORM\ManyToOne(targetEntity="MyName\MyBundle\Entity\User")
*/
protected $user;
/**
* #var json_array $details
*
* #ORM\Column(name="details", type="json_array", nullable=false)
*/
protected $details;
/**
* #var \DateTime $date
*
* #ORM\Column(name="date", type="datetime", nullable=true)
*/
protected $date;
/**
* #var integer $denied
*
* #ORM\Column(name="denied", type="integer", nullable=false)
*/
protected $denied = 0;
/**
* #var Application
*
* #ORM\ManyToOne(targetEntity="Application", inversedBy="userApplications")
*/
protected $application;
/**
* #param Application $application
*/
public function setApplication($application)
{
$this->application = $application;
}
/**
* #return Application
*/
public function getApplication()
{
return $this->application;
}
/**
* #param \DateTime $date
*/
public function setDate($date)
{
$this->date = $date;
}
/**
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* #param int $denied
*/
public function setDenied($denied)
{
$this->denied = $denied;
}
/**
* #return int
*/
public function getDenied()
{
return $this->denied;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \MyName\MyBundle\Entity\User $user
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* #return \MyName\MyBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* #param \MyName\MyBundle\Entity\json_array $details
*/
public function setDetails($details)
{
$this->details = $details;
}
/**
* #return \MyName\MyBundle\Entity\json_array
*/
public function getDetails()
{
return $this->details;
}
public function getApplicationEntityName()
{
return "MyNameModuleApplicationBundle:Application";
}
public function __toString()
{
return "";
}
}
Entity Application:
<?php
namespace MyName\Module\ApplicationBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* MyName\Module\ApplicationBundle\Entity\Application
*
* #ORM\Table(name="application")
* #ORM\Entity
*/
class Application
{
const FIELD_NAME = "NAME";
const FIELD_TYPE = "TYPE";
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #var integer $id
*/
protected $id;
/**
* #var Rank
*
* #ORM\ManyToOne(targetEntity="\MyName\MyBundle\Entity\Rank")
* #ORM\JoinColumn(name="rank_id", referencedColumnName="id", nullable=false)
*/
protected $rank;
/**
* #var Website
*
* #ORM\ManyToOne(targetEntity="\MyName\MyBundle\Entity\Website")
* #ORM\JoinColumn(name="website_id", referencedColumnName="id", nullable=false)
*/
protected $website;
/**
* #var string $name
*
* #ORM\Column(name="application_name", type="string", nullable=false)
*/
protected $name;
/**
* #var string $enabled
*
* #ORM\Column(name="application_enabled", type="integer", nullable=false)
*/
protected $enabled = 0;
/**
* #var array $fields
*
* #ORM\Column(name="application_fields", type="json_array", nullable=true)
*/
protected $fields;
/**
*
* #ORM\OneToMany(targetEntity="UserApplication", mappedBy="application")
*/
protected $userApplications;
public function __construct()
{
$this->date = new \DateTime("now");
$this->userApplications = new ArrayCollection();
}
/**
* #param string $enabled
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
}
/**
* #return string
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* #param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \MyName\MyBundle\Entity\Rank $rank
*/
public function setRank($rank)
{
$this->rank = $rank;
}
/**
* #return \MyName\MyBundle\Entity\Rank
*/
public function getRank()
{
return $this->rank;
}
/**
* #param \MyName\MyBundle\Entity\Website $website
*/
public function setWebsite($website)
{
$this->website = $website;
}
/**
* #return \MyName\MyBundle\Entity\Website
*/
public function getWebsite()
{
return $this->website;
}
/**
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param array $fields
*/
public function setFields($fields)
{
$this->fields = $fields;
}
/**
* #return array
*/
public function getFields()
{
return $this->fields;
}
function __toString()
{
return $this->name;
}
/**
* #param mixed $userApplications
*/
public function setUserApplications($userApplications)
{
$this->userApplications = $userApplications;
}
/**
* #return mixed
*/
public function getUserApplications()
{
return $this->userApplications;
}
}

I apparently had existing records which were conflicting with the application, after deleting those everything worked as supposed to. That was the reason why it was working on the development environment and not in the production.
Thanks for all the support

Related

Why my symfony entity is not managed?

I have a Portfolio entity which is working well to create or update but I can't delete it. Symfony throws this error:
Entity matthieu-appriou is not managed. An entity is managed if its
fetched from the database or registered as new through
EntityManager#persist
Here is my entity:
<?php
namespace CreasensoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SensoBundle\Entity\Talent;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use JMS\Serializer\Annotation\MaxDepth;
use JMS\Serializer\Annotation\Exclude;
/**
* Portfolio
*
* #ORM\Entity
* #ORM\Table(name="portfolio")
* #ORM\Entity(repositoryClass="CreasensoBundle\Repository\PortfolioRepository")
*/
class Portfolio
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean", nullable=true)
*/
private $visible;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Talent", cascade={"persist", "remove"}, inversedBy="portfolio")
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $talent;
/**
* #Exclude
* #ORM\OneToOne(targetEntity="SensoBundle\Entity\Image", cascade={"persist", "remove"})
* #ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $image;
/**
* #var string
*
* #ORM\Column(name="folio_label", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $folioLabel;
/**
* #var string
*
* #ORM\Column(name="main_customers", type="string", length=400, nullable=true)
*/
private $mainCustomers;
/**
* #var string
*
* #ORM\Column(name="main_agencies", type="string", length=400, nullable=true)
*/
private $mainAgencies;
/**
* #var string
*
* #ORM\Column(name="publications", type="string", length=700, nullable=true)
*/
private $publications;
/**
* #var string
*
* #ORM\Column(name="description_title", type="string", length=400, nullable=true)
* #Gedmo\Translatable
*/
private $descriptionTitle;
/**
* #var string
*
* #ORM\Column(name="description_content", type="text", nullable=true)
* #Gedmo\Translatable
*/
private $descriptionText;
/**
* #MaxDepth(2)
* #ORM\ManyToMany(targetEntity="SensoBundle\Entity\Expertise", cascade={"persist"})
*/
private $expertises;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #var \DateTime $updated
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $mostRecentProjectDate;
/**
* #var \DateTime $featuredTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $featuredTime;
/**
* #var \DateTime $submissionTime
* #ORM\Column(type="datetime", nullable=true)
*/
private $submissionTime;
/**
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->setVisible(false);
$this->expertises = new ArrayCollection();
}
public function __toString() {
return $this->getSlug();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
public function getSlug()
{
return $this->getTalent()->getSlug();
}
/**
* Set visible
*
* #param boolean $visible
*
* #return Portfolio
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getTalent()
{
return $this->talent;
}
/**
* #param mixed $talent
*/
public function setTalent($talent)
{
$this->talent = $talent;
$talent->setPortfolio($this);
}
/**
* #return mixed
*/
public function getImage()
{
return $this->image;
}
/**
* #param mixed $image
*/
public function setImage($image)
{
if ($image) {
$image->setParentType('portfolio');
}
$this->image = $image;
}
/**
* #return string
*/
public function getMainCustomers()
{
return $this->mainCustomers;
}
/**
* #param string $mainCustomers
*/
public function setMainCustomers($mainCustomers)
{
$this->mainCustomers = $mainCustomers;
}
/**
* #return string
*/
public function getMainAgencies()
{
return $this->mainAgencies;
}
/**
* #param string $mainAgencies
*/
public function setMainAgencies($mainAgencies)
{
$this->mainAgencies = $mainAgencies;
}
/**
* #return string
*/
public function getDescriptionTitle()
{
return $this->descriptionTitle;
}
/**
* #param string $descriptionTitle
*/
public function setDescriptionTitle($descriptionTitle)
{
$this->descriptionTitle = $descriptionTitle;
}
/**
* #return string
*/
public function getDescriptionText()
{
return $this->descriptionText;
}
/**
* #param string $descriptionText
*/
public function setDescriptionText($descriptionText)
{
$this->descriptionText = $descriptionText;
}
public function addExpertise($expertise)
{
$this->expertises[] = $expertise;
return $this;
}
public function removeExpertise($expertise)
{
$this->expertises->removeElement($expertise);
}
public function getExpertises()
{
return $this->expertises;
}
public function setExpertises($expertises)
{
$this->expertises = $expertises;
}
/**
* #return mixed
*/
public function getCreated()
{
return $this->created;
}
/**
* #param mixed $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* #param \DateTime $updated
*/
public function setUpdated($updated)
{
$this->updated = $updated;
}
/**
* #return \DateTime
*/
public function getFeaturedTime()
{
return $this->featuredTime;
}
/**
* #param \DateTime $featuredTime
*/
public function setFeaturedTime($featuredTime)
{
$this->featuredTime = $featuredTime;
}
/**
* #return string
*/
public function getPublications()
{
return $this->publications;
}
/**
* #param string $publications
*/
public function setPublications($publications)
{
$this->publications = $publications;
}
/**
* #return mixed
*/
public function getSubmissionTime()
{
return $this->submissionTime;
}
/**
* #param mixed $submissionTime
*/
public function setSubmissionTime($submissionTime)
{
$this->submissionTime = $submissionTime;
}
/**
* #return string
*/
public function getFolioLabel()
{
return $this->folioLabel;
}
/**
* #param string $folioLabel
*/
public function setFolioLabel($folioLabel)
{
$this->folioLabel = $folioLabel;
}
public function getType()
{
return 'portfolio';
}
/**
* #return \DateTime
*/
public function getMostRecentProjectDate()
{
return $this->mostRecentProjectDate;
}
/**
* #param \DateTime $mostRecentProjectDate
*/
public function setMostRecentProjectDate($mostRecentProjectDate)
{
$this->mostRecentProjectDate = $mostRecentProjectDate;
}
public function setTranslatableLocale($locale)
{
$this->locale = $locale;
}
}
And here is the code sample I use to reproduce this error:
<?php
// namespace and use ...
/**
* Tool controller.
*
* #Route("/admin/test")
*/
class TestController extends Controller
{
/**
*
* #Route("/testTwo", name="testTwo")
* #Method({"GET", "POST"})
*/
public function indexTwoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$pr = $this->get('creasenso.portfolio_repo');
$p = $pr->find(32);
$em->remove($p);
$em->flush();
return new Response("<html><head></head><body><hr />Done</body></html>");
}
}
Here is the repository linked to this entity:
<?php
namespace CreasensoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* PortfolioRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PortfolioRepository extends EntityRepository
{
protected $qb;
public function init()
{
$this->qb = $this->createQueryBuilder('p');
}
public function isVisible()
{
$this->qb
->andWhere('p.visible = :visible')
->setParameter(':visible', 1);
}
public function getAllPublicPortfolioCount()
{
$this->init();
$this->isVisible();
$this->qb->select('COUNT(p)');
return $this->qb->getQuery()->getSingleScalarResult();
}
public function getQueryBuilder()
{
return $this->qb;
}
}
Do you have any clue about this behavior? Thank you very much.
You are getting your repository directly from the service container when you should be getting it from your EntityManager through getRepository().
You are not loading your entity from the entityManager that you flush so it is not managed

Sonata Admin Bundle Many-to-Many relationship not saving foreign ID

Here is my problem. I have two entities with a Many-To-Many relationship and would like to insert in a field multiple information.
I use sonata admin for administration, and here is my code:
Notification Class:
<?php
namespace App\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Notification
*
* #ORM\Table(name="notification")
* #ORM\Entity
*/
class Notification {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="message", type="string", length=255)
*/
private $message;
/**
* #ORM\ManyToMany(targetEntity="Etudiant",mappedBy="notification")
*/
private $etudiant;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set message
*
* #param string $message
* #return Notification
*/
public function setMessage($message) {
$this->message = $message;
return $this;
}
/**
* Get message
*
* #return string
*/
public function getMessage() {
return $this->message;
}
public function __toString() {
return $this->message;
}
public function __construct() {
$this->etudiant = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setEtudiant($etudiant) {
if (count($etudiant) > 0) {
foreach ($etudiant as $i) {
$this->addEtudiant($i);
}
}
return $this;
}
/**
* Add etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
* #return Notification
*/
public function addEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$this->etudiant[] = $etudiant;
return $this;
}
/**
* Remove etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
*/
public function removeEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$this->etudiant->removeElement($etudiant);
}
/**
* Get etudiant
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEtudiant()
{
return $this->etudiant;
}
}
Etudiant Class:
<?php
namespace App\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Etudiant
*
* #ORM\Table(name="etudiant")
* #ORM\Entity
*/
class Etudiant{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var \DateTime
*
* #ORM\Column(name="date_naissance", type="datetime")
*/
private $dateNaissance;
/**
* #var string
*
* #ORM\Column(name="adresse", type="text")
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var int
*
* #ORM\Column(name="telephone", type="integer")
*/
private $telephone;
/**
* #var string
*
* #ORM\Column(name="num_inscription", type="string", length=255)
*/
private $numInscription;
/**
* #var \DateTime
*
* #ORM\Column(name="date_inscription", type="datetime")
*/
private $dateInscription;
/**
* #var int
*
* #ORM\Column(name="frais_scolarite", type="integer")
*/
private $fraisScolarite;
/**
* #ORM\ManyToMany(targetEntity="Notification",inversedBy="etudiant")
*#ORM\JoinColumn(name="user_notificaiton")
*/
private $notification;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return Etudiant
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
* #return Etudiant
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set dateNaissance
*
* #param \DateTime $dateNaissance
* #return Etudiant
*/
public function setDateNaissance($dateNaissance)
{
$this->dateNaissance = $dateNaissance;
return $this;
}
/**
* Get dateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->dateNaissance;
}
/**
* Set adresse
*
* #param string $adresse
* #return Etudiant
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set email
*
* #param string $email
* #return Etudiant
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set telephone
*
* #param integer $telephone
* #return Etudiant
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return integer
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Set numInscription
*
* #param string $numInscription
* #return Etudiant
*/
public function setNumInscription($numInscription)
{
$this->numInscription = $numInscription;
return $this;
}
/**
* Get numInscription
*
* #return string
*/
public function getNumInscription()
{
return $this->numInscription;
}
/**
* Set dateInscription
*
* #param \DateTime $dateInscription
* #return Etudiant
*/
public function setDateInscription($dateInscription)
{
$this->dateInscription = $dateInscription;
return $this;
}
/**
* Get dateInscription
*
* #return \DateTime
*/
public function getDateInscription()
{
return $this->dateInscription;
}
/**
* Set fraisScolarite
*
* #param integer $fraisScolarite
* #return Etudiant
*/
public function setFraisScolarite($fraisScolarite)
{
$this->fraisScolarite = $fraisScolarite;
return $this;
}
/**
* Get fraisScolarite
*
* #return integer
*/
public function getFraisScolarite()
{
return $this->fraisScolarite;
}
public function __toString() {
return $this->nom;
}
public function __construct() {
$this->notification = new \Doctrine\Common\Collections\ArrayCollection();
}
function setNotification($notification) {
if (count($notification) > 0) {
foreach ($notification as $i) {
$this->addEtudiant($i);
}
}
return $this;
}
/**
* Add notification
*
* #param \App\BlogBundle\Entity\Notification $notification
* #return Etudiant
*/
public function addNotification(\App\BlogBundle\Entity\Notification $notification)
{
$this->notification[] = $notification;
return $this;
}
/**
* Remove notification
*
* #param \App\BlogBundle\Entity\Notification $notification
*/
public function removeNotification(\App\BlogBundle\Entity\Notification $notification)
{
$this->notification->removeElement($notification);
}
/**
* Get notification
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNotification()
{
return $this->notification;
}
}
Finally My NotificationAdmin:
<?php
namespace App\BlogBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
class NotificationAdmin extends Admin {
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper) {
$formMapper
->add('message', 'text')
->add('etudiant', 'sonata_type_model', array(
'required' => false,
'multiple' => true
))
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
$datagridMapper
->add('message')
->add('etudiant')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper) {
$listMapper
->addIdentifier('message')
->add('etudiant')
;
}
// Fields to be shown on show action
protected function configureShowFields(ShowMapper $showMapper) {
$showMapper
->add('id')
->add('nom')
;
}
public function prePersist($notification){
$this->preUpdate($notification);
}
public function preUpdate($notification){
$notification->setEtudiant($notification);
}
public function getBatchActions() {
// retrieve the default batch actions (currently only delete)
$actions = parent::getBatchActions();
if (
$this->hasRoute('edit') && $this->isGranted('EDIT') &&
$this->hasRoute('delete') && $this->isGranted('DELETE')
) {
$actions['merge'] = array(
'label' => 'action_merge',
'translation_domain' => 'SonataAdminBundle',
'ask_confirmation' => true
);
}
return $actions;
}
}
And there is nothing in my table "etudiant_notification".
Please make the following changes (bold lines) to your code:
Notification.php
/**
* Add etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
* #return Notification
*/
public function addEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$etudiant->addNotification($this);
$this->etudiant[] = $etudiant;
return $this;
}
Etudiant.php
/**
* Add notification
*
* #param \App\BlogBundle\Entity\Notification $notification
* #return Etudiant
*/
public function addNotification(\App\BlogBundle\Entity\Notification $notification)
{
$notification->addEtudiant($this);
$this->notification[] = $notification;
return $this;
}
and check what happens. No guarantee, but you can give it a try. Bonne chance!

Symfony2 After form submit entity not extended on base entity

In editAction method of controller I tried to edit existed entities in class table inheritance.
But after form submit I get error:
Neither the property "id" nor one of the methods
"addId()"/"removeId()", "setId()", "id()", "__set()" or "__call()"
exist and have public access in class "AdBundle\Entity\AdFlat".
Why AdFlat entity not extended of AdBase entity?
Base entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdBase
*
* #ORM\Table(name="ad_base")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdBaseRepository")
* #ORM\HasLifecycleCallbacks()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
"flat" = "AdFlat"
* })
*/
abstract class AdBase
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdCategory")
*/
private $category;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Field Location should not be blank")
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank(message="Not specified Title")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Assert\NotBlank(message="Not specified Description")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="ad")
*/
private $photos;
/**
* #ORM\Column(type="float")
* #Assert\NotBlank()
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdPriceType")
*/
private $priceType;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean")
*/
private $visible = false;
/**
* #ORM\Column(type="boolean")
*/
private $active = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set author
*
* #param string $author
*
* #return AdBase
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Set title
*
* #param string $title
*
* #return AdBase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return AdBase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set photos
*
* #param string $photos
*
* #return AdBase
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
/**
* Get photos
*
* #return string
*/
public function getPhotos()
{
return $this->photos;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getPriceType()
{
return $this->priceType;
}
/**
* #param mixed $priceType
*/
public function setPriceType($priceType)
{
$this->priceType = $priceType;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return AdBase
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param string $updatedAt
*
* #return AdBase
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set visible
*
* #param boolean $visible
*
* #return AdBase
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #ORM\PrePersist()
*/
public function prePersist()
{
$this->author = 'voodoo';
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->location = 'Donetsk';
}
/**
* #ORM\PreUpdate()
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
Extended entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdFlat
*
* #ORM\Table(name="ad_flat")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdFlatRepository")
*/
class AdFlat extends AdBase
{
/**
* #var integer
*
* #ORM\Column(type="integer")
* #Assert\NotBlank(message="ad_flat.rooms.not_blank")
*/
private $rooms;
/**
* #var float
*
* #ORM\Column(name="square", type="float", nullable=true)
*/
private $square;
/**
* #var float
*
* #ORM\Column(name="liveSquare", type="float", nullable=true)
*/
private $liveSquare;
/**
* #var float
*
* #ORM\Column(type="float", nullable=true)
*/
private $kitchenSquare;
/**
* #var int
*
* #ORM\Column(name="floor", type="integer")
*/
private $floor;
/**
* #var int
*
* #ORM\Column(name="floors", type="integer")
*/
private $floors;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWallType")
*/
private $wallType;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWCType")
*/
private $wcType;
/**
* #return mixed
*/
public function getRooms()
{
return $this->rooms;
}
/**
* #param mixed $rooms
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
}
/**
* Set square
*
* #param float $square
*
* #return AdFlat
*/
public function setSquare($square)
{
$this->square = $square;
return $this;
}
/**
* Get square
*
* #return float
*/
public function getSquare()
{
return $this->square;
}
/**
* Set liveSquare
*
* #param float $liveSquare
*
* #return AdFlat
*/
public function setLiveSquare($liveSquare)
{
$this->liveSquare = $liveSquare;
return $this;
}
/**
* Get liveSquare
*
* #return float
*/
public function getLiveSquare()
{
return $this->liveSquare;
}
/**
* #return float
*/
public function getKitchenSquare()
{
return $this->kitchenSquare;
}
/**
* #param float $kitchenSquare
*/
public function setKitchenSquare($kitchenSquare)
{
$this->kitchenSquare = $kitchenSquare;
}
/**
* Set floor
*
* #param integer $floor
*
* #return AdFlat
*/
public function setFloor($floor)
{
$this->floor = $floor;
return $this;
}
/**
* Get floor
*
* #return int
*/
public function getFloor()
{
return $this->floor;
}
/**
* Set floors
*
* #param integer $floors
*
* #return AdFlat
*/
public function setFloors($floors)
{
$this->floors = $floors;
return $this;
}
/**
* Get floors
*
* #return int
*/
public function getFloors()
{
return $this->floors;
}
/**
* Set wallType
*
* #param string $wallType
*
* #return AdFlat
*/
public function setWallType($wallType)
{
$this->wallType = $wallType;
return $this;
}
/**
* Get wallType
*
* #return string
*/
public function getWallType()
{
return $this->wallType;
}
/**
* Set wcType
*
* #param string $wcType
*
* #return AdFlat
*/
public function setWcType($wcType)
{
$this->wcType = $wcType;
return $this;
}
/**
* Get wcType
*
* #return string
*/
public function getWcType()
{
return $this->wcType;
}
}
In controller:
public function editAction(Request $request)
{
$adId = $request->get('id');
if (!$adId) {
return $this->renderError('Unknown Ad');
}
$adEntity = $this->getDoctrine()->getRepository('AdBundle:AdBase')->find($adId);
if (null === $adEntity) {
return $this->renderError('Unknown Ad');
}
$reflection = new \ReflectionClass($adEntity);
$adForm = $this->getForm($reflection->getShortName());
$form = $this->createForm($adForm, $adEntity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($adEntity);
$em->flush();
return $this->redirectToRoute('ad_bundle_ad_view', array(
'id' => $adEntity->getId()
));
}
return $this->render('AdBundle:Ad:edit-ad-flat.html.twig', array(
'form' => $form->createView()
));
}
private function renderError($message = '')
{
return $this->render('::error.html.twig', array(
'error' => $message
));
}
private function getEntity($className)
{
$entityName = 'AdBundle\Entity\\' . $className;
return new $entityName();
}
private function getForm($className)
{
$formName = 'AdBundle\Form\Type\\' . $className . 'Type';
return new $formName();
}
The error message simply states that you are missing a way to set the entity's $id property. It doesn't tell you anything about the class not extending the base class. However, your base class only defines a getter method for the $id property but no setter method.
Doctrine Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly you need to work with the MappedSuperClass here is an example

How to add properly one-to-many relationship in Doctrine 2?

I have 2 files(tables) in my Entity, and want to join Like table to Comment table.I used one to many so can connect Comment.id to Like.comment_id and can get comments likes with one selection.When I doing this and dumping $comment->getLikes() I'm getting object of this type
object(Doctrine\ORM\PersistentCollection)
When try to do something like this $comment->getLikes()->first() getting
Undefined index:commentId
So I cant get likes from database, am I doing something wrong?And if it is possible explain why its working such way?
Here is comment Entity.
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="comments")
*/
class Comment extends Entity
{
/**
*
* /**
* #Column(type="string", length=255)
* #var string
*/
protected $url;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $description;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #Column(name="lng", type="float")
* #var float
*/
protected $lng;
/**
* #Column(name="lat", type="float")
* #var float
*/
protected $lat;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $tags;
/**
* #var Like
* #OneToMany(targetEntity="Like", mappedBy="commentId")
**/
protected $likes;
/**
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* #return float
*/
public function getLong()
{
return $this->lng;
}
/**
* #param float $lng
*/
public function setLong($lng)
{
$this->lng = $lng;
}
/**
* #return float
*/
public function getLat()
{
return $this->lat;
}
/**
* #param float $lat
*/
public function setLat($lat)
{
$this->lat = $lat;
}
/**
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* #return array()
*/
public function getLikes()
{
return $this->likes;
}
}
an here is Like Entity
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="like")
*/
class Like extends Entity
{
/**
* #Column(name="commentId", type="integer")
* #var int
*/
protected $commentId;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #return int
*/
public function getCommentId()
{
return $this->commentId;
}
/**
* #param int $commentId
*/
public function setCommentId($commentId)
{
$this->commentId = $commentId;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
}
class Comment
{
/**
* #Id
* #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $url;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $description;
/**
* #Column(name="userId", type="integer")
* #var int
*/
protected $userId;
/**
* #Column(name="lng", type="float")
* #var float
*/
protected $lng;
/**
* #Column(name="lat", type="float")
* #var float
*/
protected $lat;
/**
* #Column(type="string", length=255)
* #var string
*/
protected $tags;
/**
* #OneToMany(targetEntity="Like", mappedBy="comment")
*/
protected $likes;
public function __construct()
{
$this->likes = new ArrayCollection();
}
/**
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
/**
* #return float
*/
public function getLong()
{
return $this->lng;
}
/**
* #param float $lng
*/
public function setLong($lng)
{
$this->lng = $lng;
}
/**
* #return float
*/
public function getLat()
{
return $this->lat;
}
/**
* #param float $lat
*/
public function setLat($lat)
{
$this->lat = $lat;
}
/**
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* #param Like $like
*/
public function addLike(Like $like)
{
$this->likes->add($like);
$like->setComment($this);
}
/**
* #return ArrayCollection
*/
public function getLikes()
{
return $this->likes;
}
}
/**
* #Entity
* #Table(name="likes")
*/
class Like
{
/**
* #Id
* #Column(type="integer")
* #GeneratedValue
*/
private $id;
/**
* #ManyToOne(targetEntity="Comment", inversedBy="likes")
*/
protected $comment;
/**
* #param mixed $comment
*/
public function setComment(Comment $comment)
{
$this->comment = $comment;
}
/**
* #Column(name="userId", type="integer")
*/
protected $userId;
/**
* #return int
*/
public function getUserId()
{
return $this->userId;
}
/**
* #param int $userId
*/
public function setUserId($userId)
{
$this->userId = $userId;
}
}
FYI : Change like to likes or others because mysql keyword LIKE

Select entities where referenced objects property is equals value

Right now i try to wrap my head around Doctrine2.
So i have the following structure:
I have an article entity:
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="article")
*/
class Article extends BaseEntity {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\OneToMany(targetEntity="ArticleRevision", mappedBy="article", cascade={"persist"})
* #var ArrayCollection
*/
private $articleRevisions;
/**
* #ORM\ManyToOne(targetEntity="ArticleRevision")
* #ORM\JoinColumn(name="currentRevisionId", referencedColumnName="id", nullable=true)
* #var ArticleRevision
*/
private $currentRevision;
public function __construct(array $options = null) {
$this->articleRevisions = new ArrayCollection();
parent::__construct($options);
}
/**
* #return int
*/
public function getId() {
return $this->id;
}
/**
* #param int $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #param ArticleRevision $articleRevision
*/
public function addArticleRevision($articleRevision) {
$this->articleRevisions[] = $articleRevision;
$articleRevision->setArticle($this);
}
/**
* #return ArrayCollection
*/
public function getArticleRevisions() {
return $this->articleRevisions;
}
/**
* #return ArticleRevision
*/
public function getCurrentRevision() {
return $this->currentRevision;
}
/**
* #param ArticleRevision $articleRevision
*/
public function setCurrentRevision($articleRevision) {
$this->currentRevision = $articleRevision;
}
}
that has articleRevisions and references its current revision:
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="articlerevision")
*/
class ArticleRevision extends BaseEntity {
const TYPE_RELEASE = "release";
const TYPE_DRAFT = "draft";
const TYPE_AUTOSAVE = "autosave";
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
* #var int
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Category")
* #ORM\JoinColumn(name="categoryId", referencedColumnName="id")
* #var Category
**/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Article", inversedBy="articleRevisions")
* #ORM\JoinColumn(name="articleId", referencedColumnName="id")
* #var Article
**/
private $article;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $urlParam;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $copyright;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $supertitle;
/**
* #ORM\Column(type="string")
* #var string
*/
protected $title;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $teaser;
/**
* #ORM\Column(type="text")
* #var string
*/
protected $text;
/**
* #ORM\ManyToOne(targetEntity="ArticleRevision")
* #ORM\JoinColumn(name="previousRevisionId", referencedColumnName="id", nullable=true)
* #var ArticleRevision
*/
private $previousRevision;
public function __construct(array $options = null) {
parent::__construct($options);
}
/**
* #return int
*/
public function getId() {
return $this->id;
}
/**
* #param int $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* #return Category
*/
public function getCategory() {
return $this->category;
}
/**
* #param Category $category
*/
public function setCategory($category){
$this->category = $category;
}
/**
* #return Article
*/
public function getArticle() {
return $this->article;
}
/**
* #param Article $article
*/
public function setArticle($article) {
$this->article = $article;
}
/**
* #return string
*/
public function getCopyright() {
return $this->copyright;
}
/**
* #param string $copyright
*/
public function setCopyright($copyright) {
$this->copyright = $copyright;
}
/**
* #return string
*/
public function getUrlParam() {
return $this->urlParam;
}
/**
* #param string $urlParam
*/
public function setUrlParam($urlParam) {
$this->urlParam = $urlParam;
}
/**
* #return string
*/
public function getSupertitle() {
return $this->supertitle;
}
/**
* #param string $supertitle
*/
public function setSupertitle($supertitle) {
$this->supertitle = $supertitle;
}
/**
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* #param string $title
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* #return string
*/
public function getTeaser() {
return $this->teaser;
}
/**
* #param string $teaser
*/
public function setTeaser($teaser) {
$this->teaser = $teaser;
}
/**
* #return string
*/
public function getText() {
return $this->text;
}
/**
* #param string $text
*/
public function setText($text) {
$this->text = $text;
}
/**
* #return ArticleRevision
*/
public function getPreviousRevision() {
return $this->previousRevision;
}
/**
* #param ArticleRevision $previousRevision
*/
public function setPreviousRevision($previousRevision) {
$this->previousRevision = $previousRevision;
}
}
What i am trying to achieve is to select every article, where the categoryId of the currentRevision is for example 1.
I've tried:
$qb = $this->getRepository()->createQueryBuilder('a');
$qb->leftJoin('a.currentRevision', 'r')
->where('r.category = :category')
->setParameters(array('category' => $category));
return $qb->getQuery()->getResult();
Where $category is an int or the Application\Entity\Category. Both is returning an empty array. Can you point me in the right direction?
Any help is appreciated!
EDIT
Ouput of $qb->__toString():
SELECT a FROM Application\Entity\Article a LEFT JOIN a.currentRevision
r WHERE r.category = :category
r.category = :category, reference to Entity Category not to scalar field, you should join also Category and change condition to something like that:
$qb = $this->getRepository()->createQueryBuilder('a');
$qb->leftJoin('a.currentRevision', 'r')
->leftJoin('r.category', 'c')
->where('c.id = :category')
->setParameters(array('category' => $category));
return $qb->getQuery()->getResult();

Categories