Many to One to Many doctrine, persist only one side - php

I have a system with two tables and a join table. Reuniao have many Servidor and a Servidor have many Reuniao. For this I have a reuniao table, servidor table and reuniaoservidor table. I want to persist a reuniao with many existing servidor, but I don't want to persist a servidor when a reuniao is persisted. The problem is...
When I try to persist a reuniao doctrine says to me:
"A new entity was found through the relationship 'SistemaIfnmg\Entity\Reuniao#servidores' that was not configured to cascade persist operations for entity: SistemaIfnmg\Entity\ReuniaoServidor#000000006a69473200007f33ddb737e2. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'SistemaIfnmg\Entity\ReuniaoServidor#__toString()' to get a clue."
The Entyties:
Reuniao.php
namespace SistemaIfnmg\Entity;
use SistemaIfnmg\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="reuniao")
* #ORM\HasLifecycleCallbacks()
*/
class Reuniao
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $titulo;
/**
* #ORM\Column(type="string", length=255)
*/
private $descricao;
/**
* #ORM\Column(type="datetime")
*/
private $data;
/**
* #ORM\OneToMany(targetEntity="SistemaIfnmg\Entity\ReuniaoServidor", mappedBy="reuniaofk")
*/
private $servidores;
public function __construct(){
$this->servidores = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* #param string $titulo
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
}
/**
* #return string
*/
public function getDescricao()
{
return $this->descricao;
}
/**
* #param string $descricao
*/
public function setDescricao($descricao)
{
$this->descricao = $descricao;
}
/**
* #return string
*/
public function getData()
{
return $this->data;
}
/**
* #param string $data
*/
public function setData($data)
{
$this->data = $data;
}
/**
* Add servidores
* #param \SistemaIfnmg\Entity\ReuniaoServidor $servidor
* #return Reuniao
*/
public function addServidor(\SistemaIfnmg\Entity\ReuniaoServidor $servidor){
$this->servidores[] = $servidor;
}
/**
* Remove servidor
*
* #param \SistemaIfnmg\Entity\ReuniaoServidor $servidor
*/
public function removeServidor(\SistemaIfnmg\Entity\ReuniaoServidor $servidor){
$this->servidores->removeElement($servidor);
}
/**
* Get servidores
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServidores(){
return $this->servidores;
}
}
?>
Servidor.php
<?php
namespace SistemaIfnmg\Entity;
use SistemaIfnmg\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
* #ORM\Table(name="servidor")
*/
class Servidor
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #var integer $id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nome", type="string", length=255)
*/
private $nome;
/**
* #var string
*
* #ORM\Column(name="sobrenome", type="string", length=255)
*/
private $sobrenome;
/**
* #var string
*
* #ORM\Column(name="cargo", type="string", length=255)
*/
private $cargo;
/**
* #var string
*
* #ORM\Column(name="matricula", type="string", length=255)
*/
private $matricula;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get nome
*
* #return string
*/
public function getNome()
{
return $this->nome;
}
/**
* Set nome
*
* #param string $nome
*/
public function setNome($nome)
{
$this->nome = $nome;
}
/**
* Get sobrenome
*
* #return string
*/
public function getSobrenome()
{
return $this->sobrenome;
}
/**
* Set sobrenome
* #param string $sobrenome
*/
public function setSobrenome($sobrenome)
{
$this->sobrenome = $sobrenome;
}
/**
* Get cargo
*
* #return string
*/
public function getCargo()
{
return $this->cargo;
}
/**
* Set cargo
*
* #param string $cargo
*/
public function setCargo($cargo)
{
$this->cargo = $cargo;
}
/**
* Get matricula
*
* #return string
*/
public function getMatricula()
{
return $this->matricula;
}
/**
* Set matricula
*
* #param string $matricula
*/
public function setMatricula($matricula)
{
$this->matricula = $matricula;
}
}
?>
ReuniadoServidor.php
<?php
namespace SistemaIfnmg\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ReuniaoServidor
*
* #ORM\Table(name="reuniaoservidor", indexes={#ORM\Index(name="fk_Reuniao_has_Servidor_Reuniao1_idx", columns={"reuniaofk"}), #ORM\Index(name="fk_Reuniao_has_Servidor_Servidor1_idx", columns= {"servidorfk"})})
* #ORM\Entity
*/
class ReuniaoServidor
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="SistemaIfnmg\Entity\Reuniao", inversedBy="servidores", cascade={"persist"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="reuniaofk", referencedColumnName="id")
* })
*/
private $reuniaofk;
/**
* #ORM\ManyToOne(targetEntity="SistemaIfnmg\Entity\Servidor", inversedBy="servidores")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="servidorfk", referencedColumnName="id")
* })
*/
private $servidorfk;
/**
* Get id
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Get reuniaofk
* #return \SistemaIfnmg\Entity\Reuniao
*/
public function getReuniaofk()
{
return $this->reuniaofk;
}
/**
* Set reuniaofk
* #param \SistemaIfnmg\Entity\Reuniao $reuniaofk
* #return ReuniaoServidor
*/
public function setReuniaofk($reuniaofk)
{
$this->reuniaofk = $reuniaofk;
return $this;
}
/**
* Get servidorfk
* #return \SistemaIfnmg\Entity\Servidor
*/
public function getServidorfk()
{
return $this->servidorfk;
}
/**
* Set servidorfk
* #param \SistemaIfnmg\Entity\Servidor $servidorfk
* #return ReuniaoServidor
*/
public function setServidorfk($servidorfk)
{
$this->servidorfk = $servidorfk;
return $this;
}
}
?>
I've been trying to fix this error for a long time, please, help??
Thanks a lot

You don't need the entity that joins Reuniao to Servidor (the ReuniaoServidor entity) as Doctrine takes care of the join table for you. You just need to specify the join columns in the JoinTable mapping.
In Reuniao.php change the mapping of servidores to:
/**
* #ORM\ManyToMany(targetEntity="SistemaIfnmg\Entity\Servidor")
* #ORM\JoinTable(name="reuniao_servidor",
* joinColumns={#ORM\JoinColumn(name="ruuniao_id", referencedColumnName="id")},
* inverseJoinColumns{#ORM\JoinColumn(name="servidor_id", referencedColumnName="id")}
* )
*/
private $servidores;
also add a constructor that initializes the array for the collection
public function __construct()
{
$this->servidores = new ArrayCollection();
}
See https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#many-to-many-unidirectional

Related

WebfactoryPolyglotBundle use causes error "No mapping found for field 'id' on class 'AppBundle\Entity\Film'."

I use the Symfony version 3.4.0 and I try to use this bundle to translate entities : https://github.com/webfactory/WebfactoryPolyglotBundle
So I created two entities ( Film and FilmTranslation ) for the test
Here my Film.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Webfactory\Bundle\PolyglotBundle\Annotation as Polyglot;
use Webfactory\Bundle\PolyglotBundle\TranslatableInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Film
*
* #ORM\Table(name="film")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilmRepository")
* #Polyglot\Locale(primary="fr_FR")
*/
class Film
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Polyglot\TranslationCollection
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Titre", type="string", length=255, unique=true)
* #Polyglot\Translatable
* #var string|TranslatableInterface
*/
private $titre;
/**
* #ORM\OneToMany(targetEntity="FilmTranslation", mappedBy="entity")
* #Polyglot\TranslationCollection
* #var Collection
*/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
*
* #return Film
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Add translation
*
* #param \AppBundle\Entity\FilmTranslation $translation
*
* #return Film
*/
public function addTranslation(\AppBundle\Entity\FilmTranslation $translation)
{
$this->translations[] = $translation;
return $this;
}
/**
* Remove translation
*
* #param \AppBundle\Entity\FilmTranslation $translation
*/
public function removeTranslation(\AppBundle\Entity\FilmTranslation $translation)
{
$this->translations->removeElement($translation);
}
/**
* Get translations
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTranslations()
{
return $this->translations;
}
}
And here my FilmTranslation.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Webfactory\Bundle\PolyglotBundle\Entity\BaseTranslation;
/**
* FilmTranslation
*
* #ORM\Table(name="film_translation")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilmTranslationRepository")
* #ORM\Table(
* uniqueConstraints = {
* #ORM\UniqueConstraint(columns={"entity_id", "locale"})
* }
* )
*/
class FilmTranslation extends BaseTranslation
{
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255, unique=true)
*/
private $titre;
/**
* #ORM\ManyToOne(targetEntity="Film", inversedBy="translations")
* #var Film
*/
protected $entity;
/**
* Set titre
*
* #param string $titre
*
* #return FilmTranslation
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set locale
*
* #param string $locale
*
* #return FilmTranslation
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Set entity
*
* #param \AppBundle\Entity\Film $entity
*
* #return FilmTranslation
*/
public function setEntity(\AppBundle\Entity\Film $entity = null)
{
$this->entity = $entity;
return $this;
}
/**
* Get entity
*
* #return \AppBundle\Entity\Film
*/
public function getEntity()
{
return $this->entity;
}
}
I'm able to create a form but when I try to persist and flush I've the following error :
No mapping found for field 'id' on class 'AppBundle\Entity\Film'.
Is something I'm doing wrong ?
So remove #Polyglot\TranslationCollection from $id annotation like this ;)
class Film
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

How to fix "Could not resolve type of column "id" of class "RelacionesBundle\Entity\Pregunta""?

Actually I've generated two entities:
-Preguntas
-Areas
I'm trying to do a many to many relationshio between these two entities.
In my DataBase I already have 3 tables:
-Pregunta (idPregunta,Titulo)
-Area (idArea,Nombre)
-areas_preguntas (idArea, idPregunta)
These are my entities:
Area:
<?php
namespace RelacionesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Area
*
* #ORM\Entity
*
* #ORM\Table(name="area")
*
*/
class Area
{
/**
* #var int
*
* #ORM\Column(name="idArea", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=255)
*/
private $nombre;
/**
* #ORM\ManyToMany(targetEntity="Pregunta", mappedBy="areas")
*/
private $preguntas;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
*
* #return Area
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Constructor
*/
public function __construct()
{
$this->preguntas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add pregunta
*
* #param \RelacionesBundle\Entity\Pregunta $pregunta
*
* #return Area
*/
public function addPregunta(\RelacionesBundle\Entity\Pregunta $pregunta)
{
$this->preguntas[] = $pregunta;
return $this;
}
/**
* Remove pregunta
*
* #param \RelacionesBundle\Entity\Pregunta $pregunta
*/
public function removePregunta(\RelacionesBundle\Entity\Pregunta $pregunta)
{
$this->preguntas->removeElement($pregunta);
}
/**
* Get preguntas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPreguntas()
{
return $this->preguntas;
}
public function __toString(){
return $this->nombre;
}
}
Pregunta:
<?php
namespace RelacionesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Pregunta
*
* #ORM\Entity
*
* #ORM\Table(name="pregunta")
*
*/
class Pregunta
{
/**
* #var int
*
* #ORM\Column(name="idPregunta", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $idPregunta;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=255)
*/
private $titulo;
/**
* #ORM\ManyToMany(targetEntity="Area", inversedBy="areas")
* #ORM\JoinTable(name="areas_preguntas")
*/
private $areas;
/**
* Get idPregunta
*
* #return integer
*/
public function getId()
{
return $this->idPregunta;
}
/**
* Set titulo
*
* #param string $titulo
*
* #return Pregunta
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Constructor
*/
public function __construct()
{
$this->areas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add area
*
* #param \RelacionesBundle\Entity\Area $area
*
* #return Pregunta
*/
public function addArea(\RelacionesBundle\Entity\Area $area)
{
$this->areas[] = $area;
return $this;
}
/**
* Remove area
*
* #param \RelacionesBundle\Entity\Area $area
*/
public function removeArea(\RelacionesBundle\Entity\Area $area)
{
$this->areas->removeElement($area);
}
/**
* Get areas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAreas()
{
return $this->areas;
}
public function __toString(){
return $this->titulo;
}
}
Actually everything works fine, the problem is when I submit the Form of Pregunta, I get that error.
Any advice? or what is wrong?
Looks like by default doctrine is looking for field with name id for JoinTable. Try change JoinTable to
/**
* #ORM\JoinTable(name="areas_preguntas",
* joinColumns={#ORM\JoinColumn(name="pregunta_id", referencedColumnName="idPregunta")},
* inverseJoinColumns={#ORMJoinColumn(name="area_id", referencedColumnName="idArea")}
* )
*/

Issue when trying to use doctrine queryBuilder

I have two entities Categorie and ChampCat with ManyToMany relation and I want to get list of categories with related ChampCat by using doctrine QueryBuilder so I have used this query:
class CategorieRepository extends \Doctrine\ORM\EntityRepository
{
public function myFindCategories(array $tab){
$em = $this->getEntityManager();
$query = $em->select(array('cat', 'ch'))
->from('AnnonceBundle\Entity\Categorie', 'cat')
->join('cat.champsCat', 'ch')
->where('cat.id In (:tabOfIds)')
->setParameter('tabOfIds', array_values($tab))
->getQuery();
return $query->getResult();
}
}
Here u can see the Categorie Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\CategorieRepository")
*/
class Categorie implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="refCat", type="string", length=100)
*/
private $refCat;
/**
* #var string
*
* #ORM\Column(name="libelleCat", type="string", length=50)
*/
private $libelleCat;
/**
* #ORM\ManyToMany(targetEntity="AnnonceBundle\Entity\ChampCat",cascade={"persist"})
*/
private $champsCat;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set refCat
*
* #param string $refCat
*
* #return Categorie
*/
public function setRefCat($refCat)
{
$this->refCat = $refCat;
return $this;
}
/**
* Get refCat
*
* #return string
*/
public function getRefCat()
{
return $this->refCat;
}
/**
* Set libelleCat
*
* #param string $libelleCat
*
* #return Categorie
*/
public function setLibelleCat($libelleCat)
{
$this->libelleCat = $libelleCat;
return $this;
}
/**
* Get libelleCat
*
* #return string
*/
public function getLibelleCat()
{
return $this->libelleCat;
}
/**
* Set champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function setChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat = null)
{
$this->champsCat = $champsCat;
return $this;
}
/**
* Get champsCat
*
* #return \AnnonceBundle\Entity\ChampCat
*/
public function getChampsCat()
{
return $this->champsCat;
}
/**
* Constructor
*/
public function __construct()
{
$this->champsCat = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function addChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat[] = $champsCat;
return $this;
}
/**
* Remove champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*/
public function removeChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat->removeElement($champsCat);
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
And this is ChamCat Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ChampCat
*
* #ORM\Table(name="champ_cat")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\ChampCatRepository")
*/
class ChampCat implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*#var string
*
* #ORM\Column(name="refCh", type="string")
*/
private $refCh;
/**
* #var string
*
* #ORM\Column(name="nom_ch", type="string", length=255)
*/
private $nomCh;
/**
* #var bool
*
* #ORM\Column(name="app_ch", type="boolean")
*/
private $appCh;
/**
* #var string
*
* #ORM\Column(name="format_ch", type="string", length=255)
*/
private $formatCh;
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->refCh;
}
/**
* Set refCh
*
* #param integer $refCh
* #return ChampCat
*/
public function setRefCh($refCh)
{
$this->refCh = $refCh;
return $this;
}
/**
* Get refCh
*
* #return integer
*/
public function getRefCh()
{
return $this->refCh;
}
/**
* Set nomCh
*
* #param string $nomCh
* #return ChampCat
*/
public function setNomCh($nomCh)
{
$this->nomCh = $nomCh;
return $this;
}
/**
* Get nomCh
*
* #return string
*/
public function getNomCh()
{
return $this->nomCh;
}
/**
* Set appCh
*
* #param boolean $appCh
* #return ChampCat
*/
public function setAppCh($appCh)
{
$this->appCh = $appCh;
return $this;
}
/**
* Get appCh
*
* #return boolean
*/
public function getAppCh()
{
return $this->appCh;
}
/**
* Set formatCh
*
* #param string $formatCh
* #return ChampCat
*/
public function setFormatCh($formatCh)
{
$this->formatCh = $formatCh;
return $this;
}
/**
* Get formatCh
*
* #return string
*/
public function getFormatCh()
{
return $this->formatCh;
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
Unfortunately this query didn't work, so what am I missing ?
Is it working with this syntax?
public function myFindCategories(array $tab){
if(count($tab) == 0) return []; //or IN() will bug with an empty array
$query = $this->createQueryBuilder('cat')
->addSelect('ch')
->innerJoin('cat.champsCat', 'ch')
->where('cat.id in (:tabOfIds)')
->setParameter('tabOfIds', $tab)
->getQuery();
return $query->getResult();
}

Symfony2 Error: Attempted to call method on class "Doctrine\Common\Collections\ArrayCollection"

I have a problem with my Symfony project. I ask question on Stack Overflow because everything seems good for me but it's apparently not...
In my project I have a OneToOne bidirectional Doctrine relation between two table named "Visiteur" and "Coordonnees".
My problem appears when I submit my visiteur form. To be clear this form persist some data in "visiteur" table and it persist some data in "coordonnees" table ("imbricated form" translation from French to English)
Then I have the error below :
Attempted to call method "setVisiteur" on class
"Doctrine\Common\Collections\ArrayCollection".
There is my visiteurHandler.php who persist handle my data below.
The error appears in line 54:
$coordonnees->setVisiteur($visiteur);
The line below help me to be sure of my data type :
var_dump(gettype($coordonnees));
I obtain : string(6) "object" which is normal.
namespace Was\RHBundle\Form;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Was\RHBundle\Entity\Visiteur;
use Was\RHBundle\Entity\Coordonnees;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
class VisiteurHandler
{
protected $form;
protected $request;
protected $em;
public function __construct(Form $form, Request $request, EntityManager $em)
{
$this->form = $form;
$this->request = $request;
$this->em = $em;
}
public function process()
{
if ($this->request->getMethod() == 'POST') {
$this->form->bind($this->request);
if ($this->form->isValid() ) {
// echo '<pre>';
// print_r($this->request);
// echo '</pre>';
// die();
$this->onSuccess($this->form->getData());
return true;
}
}
return false;
}
public function onSuccess(Visiteur $visiteur)
{
$coordonnees=$visiteur->getCoordonnees();
$adresse=$visiteur->getAdresse();
var_dump(gettype($coordonnees));
$coordonnees->setVisiteur($visiteur);
$adresse->setVisiteur($visiteur);
$this->em->persist($coordonnees);
$this->em->persist($adresse);
$visiteur->setCoordonnees($coordonnees);
$visiteur->setAdresse($adresse);
$this->em->persist($visiteur);
$this->em->flush();
}
}
This is my entity visiteur which is my main entity :
<?php
namespace Was\RHBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContext;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Was\RHBundle\Entity\Visiteur
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Was\RHBundle\Entity\VisiteurRepository")
*
*/
class Visiteur
{
public function __toString()
{
return ucwords($this->prenom . " " . $this->nom);
}
public function __construct()
{
$this->createdAt = new \DateTime();
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->coordonnees = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var datetime $createdAt
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string $nom
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string $prenom
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var date $dateDebut
*
* #ORM\Column(name="dateDebut", type="date")
*/
private $dateDebut;
/**
* #var date $dateFin
*
* #ORM\Column(name="dateFin", type="date")
*/
private $dateFin;
/**
* #var string $service
*
* #ORM\Column(name="service", type="string", length=255)
*/
private $service;
/**
* #var string $fonction
*
* #ORM\Column(name="fonction", type="string", length=255)
*/
private $fonction;
/**
* #var text $remarqueSecurite
*
* #ORM\Column(name="remarqueSecurite", type="text", nullable=true)
*/
private $remarqueSecurite;
/**
* #ORM\OneToMany(targetEntity="Vehicule", mappedBy="visiteur", cascade={"remove"})
*/
private $vehicules;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Coordonnees", mappedBy="visiteur", cascade={"remove"})
*/
private $coordonnees;
/**
* #ORM\OneToOne(targetEntity="Adresse", mappedBy="visiteur", cascade={"remove"})
*/
private $adresse;
/**
* #ORM\ManyToOne(targetEntity="Agent")
* #ORM\JoinColumn(name="agent_id", referencedColumnName="id", nullable=true)
*/
private $hote;
public function isEnCours()
{
$maintenant = new \DateTime();
if ($maintenant > $this->dateDebut && $maintenant <= $this->dateFin || $this->dateFin == null) return true;
return false;
}
public function isAncien()
{
$maintenant = new \DateTime();
if ($maintenant > $this->dateDebut && $maintenant > $this->dateFin) return true;
return false;
}
public function isFutur()
{
$maintenant = new \DateTime();
if ($maintenant < $this->dateDebut && $maintenant <= $this->dateFin || $this->dateFin == null) return true;
return false;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*/
public function setNom($nom)
{
$this->nom = $nom;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set dateDebut
*
* #param date $dateDebut
*/
public function setDateDebut($dateDebut)
{
$this->dateDebut = $dateDebut;
}
/**
* Get dateDebut
*
* #return date
*/
public function getDateDebut()
{
return $this->dateDebut;
}
/**
* Set dateFin
*
* #param date $dateFin
*/
public function setDateFin($dateFin)
{
$this->dateFin = $dateFin;
}
/**
* Get dateFin
*
* #return date
*/
public function getDateFin()
{
return $this->dateFin;
}
/**
* Set service
*
* #param string $service
*/
public function setService($service)
{
$this->service = $service;
}
/**
* Get service
*
* #return string
*/
public function getService()
{
return $this->service;
}
/**
* Set remarqueSecurite
*
* #param text $remarqueSecurite
*/
public function setRemarqueSecurite($remarqueSecurite)
{
$this->remarqueSecurite = $remarqueSecurite;
}
/**
* Get remarqueSecurite
*
* #return text
*/
public function getRemarqueSecurite()
{
return $this->remarqueSecurite;
}
/**
* Add vehicules
*
* #param Was\RHBundle\Entity\Vehicule $vehicules
*/
public function addVehicule(\Was\RHBundle\Entity\Vehicule $vehicules)
{
$this->vehicules[] = $vehicules;
}
/**
* Get vehicules
*
* #return Doctrine\Common\Collections\Collection
*/
public function getVehicules()
{
return $this->vehicules;
}
/**
* Set coordonnees
*
* #param Was\RHBundle\Entity\Coordonnees $coordonnees
*/
public function setCoordonnees(Coordonnees $coordonnees)
{
$this->coordonnees[] = $coordonnees;
//$coordonnees->setVisiteur($this);
//return $this;
}
/**
* Get coordonnees
*
* #return Was\RHBundle\Entity\Coordonnees
*/
public function getCoordonnees()
{
return $this->coordonnees;
}
/**
* Set adresse
*
* #param Was\RHBundle\Entity\Adresse $adresse
*/
public function setAdresse(\Was\RHBundle\Entity\Adresse $adresse)
{
$this->adresse = $adresse;
}
/**
* Get adresse
*
* #return Was\RHBundle\Entity\Adresse
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set createdAt
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* Get createdAt
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set fonction
*
* #param string $fonction
*/
public function setFonction($fonction)
{
$this->fonction = $fonction;
}
/**
* Get fonction
*
* #return string
*/
public function getFonction()
{
return $this->fonction;
}
/**
* Set hote
*
* #param Was\RHBundle\Entity\Agent $hote
*/
public function setHote(\Was\RHBundle\Entity\Agent $hote)
{
$this->hote = $hote;
}
/**
* Get hote
*
* #return Was\RHBundle\Entity\Agent
*/
public function getHote()
{
return $this->hote;
}
/**
* Remove vehicules
*
* #param Was\RHBundle\Entity\Vehicule $vehicules
*/
public function removeVehicule(\Was\RHBundle\Entity\Vehicule $vehicules)
{
$this->vehicules->removeElement($vehicules);
}
}
This my coordonnees Entity :
namespace Was\RHBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Was\UserBundle\Entity\User as User;
/**
* Was\RHBundle\Entity\Coordonnees
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Was\RHBundle\Entity\CoordonneesRepository")
* #UniqueEntity(fields="emailPro", message="Cet email professionnel est déjà pris.")
*/
class Coordonnees
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $telPro
*
* #ORM\Column(name="telPro", type="string", length=255, nullable=true)
*/
private $telPro;
/**
* #var string $telFax
*
* #ORM\Column(name="telFax", type="string", length=255, nullable=true)
*/
private $telFax;
/**
* #var string $telPortable
*
* #ORM\Column(name="telPortable", type="string", length=255, nullable=true)
*/
private $telPortable;
/**
* #var string $telDomicile
*
* #ORM\Column(name="telDomicile", type="string", length=255, nullable=true)
*/
private $telDomicile;
/**
* #var string $telAutre
*
* #ORM\Column(name="telAutre", type="string", length=255, nullable=true)
*/
private $telAutre;
/**
* #var string $telUrgence
*
* #ORM\Column(name="telUrgence", type="string", length=255, nullable=true)
*/
private $telUrgence;
/**
* #ORM\Column(name="contactUrgence", type="text", nullable=true)
*/
private $contactUrgence;
/**
* #ORM\Column(name="contactUrgenceUS", type="text", nullable=true)
*/
private $contactUrgenceUS;
/**
* #var string $numeroBadge
*
* #ORM\Column(name="numeroBadge", type="string", length=255, nullable=true)
*/
private $numeroBadge;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Email(message="Email personnel invalide.")
*/
private $emailPerso;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Email(message="Email professionnel invalide.")
*/
private $emailPro;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Agent", inversedBy="coordonnees")
* #ORM\JoinColumn( name="agent_id", referencedColumnName="id")
*/
private $agent;
/**
* #ORM\OneToOne(targetEntity="Was\RHBundle\Entity\Visiteur", inversedBy="coordonnees")
* #ORM\JoinColumn(name="visiteur_id", referencedColumnName="id")
*/
private $visiteur;
/**
* #var datetime $updatedAt
*
* #ORM\Column(name="updatedAt", type="datetime", nullable=true)
*/
private $updatedAt;
/**
* #ORM\ManyToOne(targetEntity="\Was\UserBundle\Entity\User")
* #ORM\JoinColumn(name="updated_by_id", referencedColumnName="id", nullable=true)
*/
private $updatedBy;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set telPro
*
* #param string $telPro
*/
public function setTelPro($telPro)
{
$this->telPro = $telPro;
}
/**
* Get telPro
*
* #return string
*/
public function getTelPro()
{
return $this->telPro;
}
/**
* Set telFax
*
* #param string $telFax
*/
public function setTelFax($telFax)
{
$this->telFax = $telFax;
}
/**
* Get telFax
*
* #return string
*/
public function getTelFax()
{
return $this->telFax;
}
/**
* Set telPortable
*
* #param string $telPortable
*/
public function setTelPortable($telPortable)
{
$this->telPortable = $telPortable;
}
/**
* Get telPortable
*
* #return string
*/
public function getTelPortable()
{
return $this->telPortable;
}
/**
* Set telDomicile
*
* #param string $telDomicile
*/
public function setTelDomicile($telDomicile)
{
$this->telDomicile = $telDomicile;
}
/**
* Get telDomicile
*
* #return string
*/
public function getTelDomicile()
{
return $this->telDomicile;
}
/**
* Set telAutre
*
* #param string $telAutre
*/
public function setTelAutre($telAutre)
{
$this->telAutre = $telAutre;
}
/**
* Get telAutre
*
* #return string
*/
public function getTelAutre()
{
return $this->telAutre;
}
/**
* Set telUrgence
*
* #param string $telUrgence
*/
public function setTelUrgence($telUrgence)
{
$this->telUrgence = $telUrgence;
}
/**
* Get telUrgence
*
* #return string
*/
public function getTelUrgence()
{
return $this->telUrgence;
}
/**
* Set agent
*
* #param Was\RHBundle\Entity\Agent $agent
*/
public function setAgent(\Was\RHBundle\Entity\Agent $agent)
{
$this->agent = $agent;
}
/**
* Get agent
*
* #return Was\RHBundle\Entity\Agent
*/
public function getAgent()
{
return $this->agent;
}
/**
* Set emailPerso
*
* #param string $emailPerso
*/
public function setEmailPerso($emailPerso)
{
$this->emailPerso = $emailPerso;
}
/**
* Get emailPerso
*
* #return string
*/
public function getEmailPerso()
{
return $this->emailPerso;
}
/**
* Set emailPro
*
* #param string $emailPro
*/
public function setEmailPro($emailPro)
{
$this->emailPro = $emailPro;
}
/**
* Get emailPro
*
* #return string
*/
public function getEmailPro()
{
return $this->emailPro;
}
/**
* Set visiteur
*
* #param Was\RHBundle\Entity\Visiteur $visiteur
*/
public function setVisiteur(\Was\RHBundle\Entity\Visiteur $visiteur)
{
$this->visiteur = $visiteur;
}
/**
* Get visiteur
*
* #return Was\RHBundle\Entity\Visiteur
*/
public function getVisiteur()
{
return $this->visiteur;
}
/**
* Set updatedAt
*
* #param datetime $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
/**
* Get updatedAt
*
* #return datetime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set updatedBy
*
* #param Was\UserBundle\Entity\User $updatedBy
*/
public function setUpdatedBy($updatedBy)
{
$this->updatedBy = $updatedBy;
}
/**
* Get updatedBy
*
* #return Was\UserBundle\Entity\User
*/
public function getUpdatedBy()
{
return $this->updatedBy;
}
/**
* Set numeroBadge
*
* #param string $numeroBadge
*/
public function setNumeroBadge($numeroBadge)
{
$this->numeroBadge = $numeroBadge;
}
/**
* Get numeroBadge
*
* #return string
*/
public function getNumeroBadge()
{
return $this->numeroBadge;
}
/**
* Set contactUrgence
*
* #param text $contactUrgence
*/
public function setContactUrgence($contactUrgence)
{
$this->contactUrgence = $contactUrgence;
}
/**
* Get contactUrgence
*
* #return text
*/
public function getContactUrgence()
{
return $this->contactUrgence;
}
/**
* Set contactUrgenceUS
*
* #param text $contactUrgenceUS
*/
public function setContactUrgenceUS($contactUrgenceUS)
{
$this->contactUrgenceUS = $contactUrgenceUS;
}
/**
* Get contactUrgenceUS
*
* #return text
*/
public function getContactUrgenceUS()
{
return $this->contactUrgenceUS;
}
}
You say (and define it with annotations) that it's a OneToOne relation.
But look in to Visiteur entity class.
You set cordonnees to be an ArrayCollection instead of single Coordonness entity object in constructor.
public function __construct()
{
$this->createdAt = new \DateTime();
$this->vehicules = new \Doctrine\Common\Collections\ArrayCollection();
$this->coordonnees = new \Doctrine\Common\Collections\ArrayCollection(); // <-- here
}
And futher in setter you use it as an array too:
/**
* Set coordonnees
*
* #param Was\RHBundle\Entity\Coordonnees $coordonnees
*/
public function setCoordonnees(Coordonnees $coordonnees)
{
$this->coordonnees[] = $coordonnees;
//$coordonnees->setVisiteur($this);
//return $this;
}
So the getter returns an array (ArrayCollection object actually) of entities.
Let's look at the problematic code:
public function onSuccess(Visiteur $visiteur)
{
$coordonnees=$visiteur->getCoordonnees(); //this returns ArrayCollection of Coordnnees entity objects
$adresse=$visiteur->getAdresse();
var_dump(gettype($coordonnees)); // yes, it says "object" because it's instance of ArrayCollection class
$coordonnees->setVisiteur($visiteur); //Now you should know, why it won't work. It's not an entity object, but ArrayCollection of entity objects.
//(...)
}
I think that $coordonneess shoudn't be an ArrayCollection since it's OneToOne relation.

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