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!
Related
In editAction method of controller I tried to edit existed entities in class table inheritance.
But after form submit I get error:
Neither the property "id" nor one of the methods
"addId()"/"removeId()", "setId()", "id()", "__set()" or "__call()"
exist and have public access in class "AdBundle\Entity\AdFlat".
Why AdFlat entity not extended of AdBase entity?
Base entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdBase
*
* #ORM\Table(name="ad_base")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdBaseRepository")
* #ORM\HasLifecycleCallbacks()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
"flat" = "AdFlat"
* })
*/
abstract class AdBase
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdCategory")
*/
private $category;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Field Location should not be blank")
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank(message="Not specified Title")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Assert\NotBlank(message="Not specified Description")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="ad")
*/
private $photos;
/**
* #ORM\Column(type="float")
* #Assert\NotBlank()
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdPriceType")
*/
private $priceType;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean")
*/
private $visible = false;
/**
* #ORM\Column(type="boolean")
*/
private $active = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set author
*
* #param string $author
*
* #return AdBase
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Set title
*
* #param string $title
*
* #return AdBase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return AdBase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set photos
*
* #param string $photos
*
* #return AdBase
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
/**
* Get photos
*
* #return string
*/
public function getPhotos()
{
return $this->photos;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getPriceType()
{
return $this->priceType;
}
/**
* #param mixed $priceType
*/
public function setPriceType($priceType)
{
$this->priceType = $priceType;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return AdBase
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param string $updatedAt
*
* #return AdBase
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set visible
*
* #param boolean $visible
*
* #return AdBase
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #ORM\PrePersist()
*/
public function prePersist()
{
$this->author = 'voodoo';
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->location = 'Donetsk';
}
/**
* #ORM\PreUpdate()
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
Extended entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdFlat
*
* #ORM\Table(name="ad_flat")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdFlatRepository")
*/
class AdFlat extends AdBase
{
/**
* #var integer
*
* #ORM\Column(type="integer")
* #Assert\NotBlank(message="ad_flat.rooms.not_blank")
*/
private $rooms;
/**
* #var float
*
* #ORM\Column(name="square", type="float", nullable=true)
*/
private $square;
/**
* #var float
*
* #ORM\Column(name="liveSquare", type="float", nullable=true)
*/
private $liveSquare;
/**
* #var float
*
* #ORM\Column(type="float", nullable=true)
*/
private $kitchenSquare;
/**
* #var int
*
* #ORM\Column(name="floor", type="integer")
*/
private $floor;
/**
* #var int
*
* #ORM\Column(name="floors", type="integer")
*/
private $floors;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWallType")
*/
private $wallType;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWCType")
*/
private $wcType;
/**
* #return mixed
*/
public function getRooms()
{
return $this->rooms;
}
/**
* #param mixed $rooms
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
}
/**
* Set square
*
* #param float $square
*
* #return AdFlat
*/
public function setSquare($square)
{
$this->square = $square;
return $this;
}
/**
* Get square
*
* #return float
*/
public function getSquare()
{
return $this->square;
}
/**
* Set liveSquare
*
* #param float $liveSquare
*
* #return AdFlat
*/
public function setLiveSquare($liveSquare)
{
$this->liveSquare = $liveSquare;
return $this;
}
/**
* Get liveSquare
*
* #return float
*/
public function getLiveSquare()
{
return $this->liveSquare;
}
/**
* #return float
*/
public function getKitchenSquare()
{
return $this->kitchenSquare;
}
/**
* #param float $kitchenSquare
*/
public function setKitchenSquare($kitchenSquare)
{
$this->kitchenSquare = $kitchenSquare;
}
/**
* Set floor
*
* #param integer $floor
*
* #return AdFlat
*/
public function setFloor($floor)
{
$this->floor = $floor;
return $this;
}
/**
* Get floor
*
* #return int
*/
public function getFloor()
{
return $this->floor;
}
/**
* Set floors
*
* #param integer $floors
*
* #return AdFlat
*/
public function setFloors($floors)
{
$this->floors = $floors;
return $this;
}
/**
* Get floors
*
* #return int
*/
public function getFloors()
{
return $this->floors;
}
/**
* Set wallType
*
* #param string $wallType
*
* #return AdFlat
*/
public function setWallType($wallType)
{
$this->wallType = $wallType;
return $this;
}
/**
* Get wallType
*
* #return string
*/
public function getWallType()
{
return $this->wallType;
}
/**
* Set wcType
*
* #param string $wcType
*
* #return AdFlat
*/
public function setWcType($wcType)
{
$this->wcType = $wcType;
return $this;
}
/**
* Get wcType
*
* #return string
*/
public function getWcType()
{
return $this->wcType;
}
}
In controller:
public function editAction(Request $request)
{
$adId = $request->get('id');
if (!$adId) {
return $this->renderError('Unknown Ad');
}
$adEntity = $this->getDoctrine()->getRepository('AdBundle:AdBase')->find($adId);
if (null === $adEntity) {
return $this->renderError('Unknown Ad');
}
$reflection = new \ReflectionClass($adEntity);
$adForm = $this->getForm($reflection->getShortName());
$form = $this->createForm($adForm, $adEntity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($adEntity);
$em->flush();
return $this->redirectToRoute('ad_bundle_ad_view', array(
'id' => $adEntity->getId()
));
}
return $this->render('AdBundle:Ad:edit-ad-flat.html.twig', array(
'form' => $form->createView()
));
}
private function renderError($message = '')
{
return $this->render('::error.html.twig', array(
'error' => $message
));
}
private function getEntity($className)
{
$entityName = 'AdBundle\Entity\\' . $className;
return new $entityName();
}
private function getForm($className)
{
$formName = 'AdBundle\Form\Type\\' . $className . 'Type';
return new $formName();
}
The error message simply states that you are missing a way to set the entity's $id property. It doesn't tell you anything about the class not extending the base class. However, your base class only defines a getter method for the $id property but no setter method.
Doctrine Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly you need to work with the MappedSuperClass here is an example
I want to find one data with findbyone option but by accesing the related object. Next you'll find the two of the entities Im using.
Caja.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
*
* #ORM\Entity
* #ORM\Table(name="caja")
*
*/
class Caja
{
/**
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Número carton")
*/
protected $numero_carton;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_inferior;
/** #ORM\Column(type="string", length=100) */
protected $contiene_libreta_limite_superior;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Libretas omitidas")
*/
protected $omite_libreta;
/**
* #ORM\Column(type="string", length=100)
* #GRID\Column(title="Total libretas")
*/
protected $total_libretas;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Juego")
* #ORM\JoinColumn(name="juego_id", referencedColumnName="id")
* */
protected $juego;
/** #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario") **/
protected $usuario;
/**
* #ORM\Column(type="datetime", nullable=true)
* #GRID\Column(title="Fecha creación")
*/
protected $fecha_creacion;
/**
* #var boolean
*
* #ORM\Column(name="estado", type="string", length=50)
* #GRID\Column(title="Estado")
*/
protected $estado;
/*
* 1 = CREADO
* 2 = ASIGNADO_A_SUPERVISOR
* 3 = FINALIZADO_CON_EXITO
* 4 = FINALIZADO_CON_OBSERVACIONES
* 5 = DESHABILITADO
*
*/
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Libreta", mappedBy="caja", cascade={"remove", "persist"})
*/
protected $libretas;
public function __construct()
{
$this->fecha_creacion = new \DateTime();
$this->libretas = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set numero_carton
*
* #param string $numeroCarton
* #return Caja
*/
public function setNumeroCarton($numeroCarton)
{
$this->numero_carton = $numeroCarton;
return $this;
}
/**
* Get numero_carton
*
* #return string
*/
public function getNumeroCarton()
{
return $this->numero_carton;
}
/**
* Set contiene_libreta_limite_inferior
*
* #param string $contieneLibretaLimiteInferior
* #return Caja
*/
public function setContieneLibretaLimiteInferior($contieneLibretaLimiteInferior)
{
$this->contiene_libreta_limite_inferior = $contieneLibretaLimiteInferior;
return $this;
}
/**
* Get contiene_libreta_limite_inferior
*
* #return string
*/
public function getContieneLibretaLimiteInferior()
{
return $this->contiene_libreta_limite_inferior;
}
/**
* Set contiene_libreta_limite_superior
*
* #param string $contieneLibretaLimiteSuperior
* #return Caja
*/
public function setContieneLibretaLimiteSuperior($contieneLibretaLimiteSuperior)
{
$this->contiene_libreta_limite_superior = $contieneLibretaLimiteSuperior;
return $this;
}
/**
* Get contiene_libreta_limite_superior
*
* #return string
*/
public function getContieneLibretaLimiteSuperior()
{
return $this->contiene_libreta_limite_superior;
}
/**
* Set omite_libreta
*
* #param string $omiteLibreta
* #return Caja
*/
public function setOmiteLibreta($omiteLibreta)
{
$this->omite_libreta = $omiteLibreta;
return $this;
}
/**
* Get omite_libreta
*
* #return string
*/
public function getOmiteLibreta()
{
return $this->omite_libreta;
}
/**
* Set total_libretas
*
* #param string $totalLibretas
* #return Caja
*/
public function setTotalLibretas($totalLibretas)
{
$this->total_libretas = $totalLibretas;
return $this;
}
/**
* Get total_libretas
*
* #return string
*/
public function getTotalLibretas()
{
return $this->total_libretas;
}
/**
* Set juego
*
* #param \PD\AppBundle\Entity\Juego $juego
* #return Caja
*/
public function setJuego(\PD\AppBundle\Entity\Juego $juego)
{
$this->juego = $juego;
}
/**
* Get juego
*
* #return \PD\AppBundle\Entity\Juego
*/
public function getJuego()
{
return $this->juego;
}
public function __toString()
{
return $this->getNumeroCarton();
}
/**
* Set usuario
*
* #param \PD\AppBundle\Entity\Usuario $usuario
* #return Caja
*/
public function setUsuario(\PD\AppBundle\Entity\Usuario $usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set fecha_creacion
*
* #param \DateTime $fechaCreacion
* #return Caja
*/
public function setFechaCreacion($fechaCreacion)
{
$this->fecha_creacion = $fechaCreacion;
return $this;
}
/**
* Get fecha_creacion
*
* #return \DateTime
*/
public function getFechaCreacion()
{
return $this->fecha_creacion;
}
/**
* Set estado
*
* #param string $estado
* #return Caja
*/
public function setEstado($estado)
{
$this->estado = $estado;
return $this;
}
/**
* Get estado
*
* #return string
*/
public function getEstado()
{
return $this->estado;
}
/**
* Add libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
* #return Caja
*/
public function addLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
//$this->libretas[] = $libretas;
//return $this;
$libretas->setCaja($this);
$this->libretas->add($libretas);
return $this;
}
/**
* Remove libretas
*
* #param \PD\AppBundle\Entity\Libreta $libretas
*/
public function removeLibreta(\PD\AppBundle\Entity\Libreta $libretas)
{
$this->libretas->removeElement($libretas);
}
/**
* Get libretas
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLibretas()
{
return $this->libretas;
}
}
Libreta.php
<?php
namespace PD\AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use APY\DataGridBundle\Grid\Mapping as GRID;
/**
* Libreta
*
* #ORM\Table()
* #ORM\Entity
*/
class Libreta
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Caja", inversedBy="libretas")
* #ORM\JoinColumn(name="caja_id", referencedColumnName="id", nullable=false)
* #Assert\Type(type="PD\AppBundle\Entity\Caja")
* #GRID\Column(field="caja.juego.nombre", title="Juego")
* #GRID\Column(field="caja.numero_carton", title="Caja")
*/
protected $caja;
/**
* #var string
*
* #ORM\Column(name="correlativo", type="string", length=10)
* #GRID\Column(title="Correlativo")
*/
private $correlativo;
/**
* #ORM\ManyToOne(targetEntity="PD\AppBundle\Entity\Usuario")
* #ORM\JoinColumn(name="vendedor_id", referencedColumnName="id", nullable=true)
* #Assert\Type(type="PD\AppBundle\Entity\Usuario")
* #GRID\Column(field="vendedor.nombre", title="Nombre vendedor")
* #GRID\Column(field="vendedor.apellidos", title="Apellidos vendedor")
*/
protected $vendedor;
/** #ORM\Column(name="precio_al_vendedor", type="decimal", scale=2) */
protected $precio_al_vendedor;
/** #ORM\Column(name="precio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Precio acumulado")
*/
protected $precio_acumulado;
/** #ORM\Column(name="premio_acumulado", type="decimal", scale=2)
* #GRID\Column(title="Premio acumulado")
*/
protected $premio_acumulado;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_asignacion_vendedor;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $fecha_estado_final;
/**
* #ORM\OneToMany(targetEntity="PD\AppBundle\Entity\Ticket", mappedBy="libreta", cascade={"persist"})
*/
protected $tickets;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set correlativo
*
* #param string $correlativo
* #return Libreta
*/
public function setCorrelativo($correlativo)
{
$this->correlativo = $correlativo;
return $this;
}
/**
* Get correlativo
*
* #return string
*/
public function getCorrelativo()
{
return $this->correlativo;
}
/**
* Set precio_al_vendedor
*
* #param string $precioAlVendedor
* #return Libreta
*/
public function setPrecioAlVendedor($precioAlVendedor)
{
$this->precio_al_vendedor = $precioAlVendedor;
return $this;
}
/**
* Get precio_al_vendedor
*
* #return string
*/
public function getPrecioAlVendedor()
{
return $this->precio_al_vendedor;
}
/**
* Set precio_acumulado
*
* #param string $precioAcumulado
* #return Libreta
*/
public function setPrecioAcumulado($precioAcumulado)
{
$this->precio_acumulado = $precioAcumulado;
return $this;
}
/**
* Get precio_acumulado
*
* #return string
*/
public function getPrecioAcumulado()
{
return $this->precio_acumulado;
}
/**
* Set fecha_asignacion_vendedor
*
* #param \DateTime $fechaAsignacionVendedor
* #return Libreta
*/
public function setFechaAsignacionVendedor($fechaAsignacionVendedor)
{
$this->fecha_asignacion_vendedor = $fechaAsignacionVendedor;
return $this;
}
/**
* Get fecha_asignacion_vendedor
*
* #return \DateTime
*/
public function getFechaAsignacionVendedor()
{
return $this->fecha_asignacion_vendedor;
}
/**
* Set fecha_estado_final
*
* #param \DateTime $fechaEstadoFinal
* #return Libreta
*/
public function setFechaEstadoFinal($fechaEstadoFinal)
{
$this->fecha_estado_final = $fechaEstadoFinal;
return $this;
}
/**
* Get fecha_estado_final
*
* #return \DateTime
*/
public function getFechaEstadoFinal()
{
return $this->fecha_estado_final;
}
/**
* Set vendedor
*
* #param \PD\AppBundle\Entity\Usuario $vendedor
* #return Libreta
*/
public function setVendedor(\PD\AppBundle\Entity\Usuario $vendedor = null)
{
$this->vendedor = $vendedor;
return $this;
}
/**
* Get vendedor
*
* #return \PD\AppBundle\Entity\Usuario
*/
public function getVendedor()
{
return $this->vendedor;
}
/**
* Set caja
*
* #param \PD\AppBundle\Entity\Caja $caja
* #return Libreta
*/
public function setCaja(\PD\AppBundle\Entity\Caja $caja = null)
{
$this->caja = $caja;
return $this;
}
/**
* Get caja
*
* #return \PD\AppBundle\Entity\Caja
*/
public function getCaja()
{
return $this->caja;
}
/**
* Constructor
*/
public function __construct()
{
$this->tickets = new \Doctrine\Common\Collections\ArrayCollection();
//$this->caja = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
* #return Libreta
*/
public function addTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
//$this->tickets[] = $tickets;
$tickets->setLibreta($this);
$this->tickets->add($tickets);
return $this;
}
/**
* Remove tickets
*
* #param \PD\AppBundle\Entity\Ticket $tickets
*/
public function removeTicket(\PD\AppBundle\Entity\Ticket $tickets)
{
$this->tickets->removeElement($tickets);
}
/**
* Get tickets
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTickets()
{
return $this->tickets;
}
public function __toString()
{
return $this->correlativo;
}
/**
* Set premio_acumulado
*
* #param string $premioAcumulado
* #return Libreta
*/
public function setPremioAcumulado($premioAcumulado)
{
$this->premio_acumulado = $premioAcumulado;
return $this;
}
/**
* Get premio_acumulado
*
* #return string
*/
public function getPremioAcumulado()
{
return $this->premio_acumulado;
}
}
And what I would like to do is to find one next row ordered by field "fecha_creacion". This is what I have that get the next row but ordered by caja ID
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja' => 'DESC'));
But what I want to know if I can do something like "array('caja.fecha_creacion' => 'DESC'));". Until now, this part of the code isn't recognizing the "fecha_creacion" field
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findOneBy(array('vendedor' => NULL), array('caja.fecha_creacion' => 'DESC'));
According to the doc, you can't pass a second parameter to the findOnyBy function.
But you can try to cheat by using the findBy methods and the position of this array :
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findNextLibreta(NULL, $actualPosicion);
...
And in your repository :
public function findNextLibreta($vendedor, $posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin(l.caja, 'c')
->where('l.vendedor = :vendedor')
->setParameter(':type', $type)
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
Thanks to #JulienBourdic I changed a little his proposal but him basically gave me the answer. The code is:
$posicion = 0;
$libreta_siguiente = $this->getDoctrine()
->getRepository('PDBundle:Libreta')
->findByNextLibreta($posicion);
Then in LibretaRepository.php
public function findByNextLibreta($posicion) {
$qb = $this->createQueryBuilder('l');
$qb->leftJoin('l.caja', 'c')
->where('l.vendedor is NULL')
->orderBy('c.fecha_creacion', 'DESC');
$results = $qb->getQuery()->getResult();
return $results[$posicion];
}
It differs a little cuz didn't know how to pass the NULL value Julien was proposing so I used l.vendedor is NULL burned in the code.
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.
I am new to Symfony2. I am not using FOS UserBundle to implement security.
Followed the Load user documentation in the main website of Symfony.
When I try to see the array of User entity it's showing empty for particular user as shown below
[roles:Acme\UserBundle\Entity\User:private] =>
Doctrine\Common\Collections\ArrayCollection Object (
[_elements:Doctrine\Common\Collections\ArrayCollection:private] =>
Array ( ) )
My User Entity class is
<?php
namespace Acme\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Acme\UserBundle\Entity\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Acme\UserBundle\Entity\Role;
/**
* Acme\Bundle\UserRegistrationBundle\Entity\User
*
* #ORM\Table(name="acme_users")
* #ORM\Entity(repositoryClass="Acme\UserBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $fname;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $lname;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=20)
*/
private $gender;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $profession;
/**
* #ORM\Column(type="date")
*/
private $date_of_birth;
/**
* #ORM\Column(type="integer")
*/
private $country_id;
/**
* #ORM\Column(type="integer")
*/
private $state_id;
/**
* #ORM\Column(type="integer")
*/
private $city_id;
/**
* #ORM\Column(type="string", length=20)
*/
private $phone_number;
/**
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
* #ORM\Column(type="integer")
*/
private $is_lock;
/**
* #ORM\Column(type="integer")
*/
private $failed_attempt;
/**
* #ORM\Column(type="string", length=32)
*/
private $salt;
/**
* #ORM\ManyToMany(targetEntity="Role",inversedBy="users")
* #var ArrayCollection $roles;
*/
private $roles;
public function __construct()
{
$this->status = true;
$this->salt = md5(uniqid(null, true));
$this->roles = new ArrayCollection();
}
/**
* Get roles (array)
*
* #return array
*/
public function getRoles()
{
return $this->roles->toArray();
}
/**
* Get user_id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fname
*
* #param string $fname
* #return User
*/
public function setFname($fname)
{
$this->fname = $fname;
return $this;
}
/**
* Get fname
*
* #return string
*/
public function getFname()
{
return $this->fname;
}
/**
* Set lname
*
* #param string $lname
* #return User
*/
public function setLname($lname)
{
$this->lname = $lname;
return $this;
}
/**
* Get lname
*
* #return string
*/
public function getLname()
{
return $this->lname;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set gender
*
* #param string $gender
* #return User
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set profession
*
* #param string $profession
* #return User
*/
public function setProfession($profession)
{
$this->profession = $profession;
return $this;
}
/**
* Get profession
*
* #return string
*/
public function getProfession()
{
return $this->profession;
}
/**
* Set date_of_birth
*
* #param \DateTime $dateOfBirth
* #return User
*/
public function setDateOfBirth($dateOfBirth)
{
$this->date_of_birth = $dateOfBirth;
return $this;
}
/**
* Get date_of_birth
*
* #return \DateTime
*/
public function getDateOfBirth()
{
return $this->date_of_birth;
}
/**
* Set country_id
*
* #param integer $countryId
* #return User
*/
public function setCountryId($countryId)
{
$this->country_id = $countryId;
return $this;
}
/**
* Get country_id
*
* #return integer
*/
public function getCountryId()
{
return $this->country_id;
}
/**
* Set state_id
*
* #param integer $stateId
* #return User
*/
public function setStateId($stateId)
{
$this->state_id = $stateId;
return $this;
}
/**
* Get state_id
*
* #return integer
*/
public function getStateId()
{
return $this->state_id;
}
/**
* Set city_id
*
* #param integer $cityId
* #return User
*/
public function setCityId($cityId)
{
$this->city_id = $cityId;
return $this;
}
/**
* Get city_id
*
* #return integer
*/
public function getCityId()
{
return $this->city_id;
}
/**
* Set phone_number
*
* #param string $phoneNumber
* #return User
*/
public function setPhoneNumber($phoneNumber)
{
$this->phone_number = $phoneNumber;
return $this;
}
/**
* Get phone_number
*
* #return string
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* Set status
*
* #param boolean $status
* #return User
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
/**
* Set is_lock
*
* #param integer $isLock
* #return User
*/
public function setIsLock($isLock)
{
$this->is_lock = $isLock;
return $this;
}
/**
* Get is_lock
*
* #return integer
*/
public function getIsLock()
{
return $this->is_lock;
}
/**
* Set failed_attempt
*
* #param integer $failedAttempt
* #return User
*/
public function setFailedAttempt($failedAttempt)
{
$this->failed_attempt = $failedAttempt;
return $this;
}
/**
* Get failed_attempt
*
* #return integer
*/
public function getFailedAttempt()
{
return $this->failed_attempt;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Add roles
*
* #param \Autograph\UserBundle\Entity\Role $roles
* #return User
*/
public function addRole(\Autograph\UserBundle\Entity\Role $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \Autograph\UserBundle\Entity\Role $roles
*/
public function removeRole(\Autograph\UserBundle\Entity\Role $roles)
{
$this->roles->removeElement($roles);
}
public function eraseCredentials() {
}
public function getUsername() {
}
public function serialize() {
}
public function unserialize($serialized) {
}
}
My Role Entity Class is
<?php
// src/Acme/UserBundle/Entity/Role.php
namespace Acme\UserBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="acme_roles")
* #ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*
* #var string $role
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*
* #var ArrayCollection $users
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
/**
* Set role
*
* #param string $role
* #return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
// ... getters and setters for each property
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add users
*
* #param \Autograph\UserBundle\Entity\User $users
* #return Role
*/
public function addUser(\Autograph\UserBundle\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* #param \Autograph\UserBundle\Entity\User $users
*/
public function removeUser(\Autograph\UserBundle\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
What is wrong?
class Accounts extends AbstractType
{
private $em;
private $accountrepo = null;
private $choices = array();
public function __construct()
{
}
public function setAccountRepository($repo)
{
$this->accountrepo = $repo;
return $this;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'choices' => $this->getChoices(),
'attr' => [
'data-dojo-type' => 'dijit/form/FilteringSelect',
],
'data_class' => 'Far\MT\AccountBundle\Entity\Account'
]);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'Accounts';
}
public function getChoices()
{
if ( count($this->choices) > 0 ) {
return $this->choices;
}
$this->choices[0] = "";
foreach ($this->accountrepo->findAll() as $account) {
$this->choices[$account->getId()] = $account->getName() . " (" .
$account->getCurrency().") ";
}
return $this->choices;
}
}
Using the code above I get the error:
Notice: Object of class
Proxies__CG__\Far\MT\AccountBundle\Entity\Account could not be
converted to int in
/workspace/tools/vendorsymfony2/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php
line 457
This only happens when I edit the record, I'm using this Type has a ChoiceList type in order to have the db values filtered and placed on the "combobox".
Any sugestions on what I can be doing wrong?
EDIT
use Doctrine\ORM\Mapping as ORM;
/**
* Movement
*
* #ORM\Entity(repositoryClass="Far\MT\AccountBundle\Entity\MovementRepository")
* #ORM\Table(name="movement")
*/
class Movement
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Date
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="MovementType")
* #ORM\JoinColumn(name="movementtype", referencedColumnName="id", unique=false)
*/
private $Type;
/**
* #var float
*
* #ORM\Column(name="value", type="float")
*/
private $value;
/**
* #var Account
*
* #ORM\ManyToOne(targetEntity="Account", cascade={"persist"})
* #ORM\JoinColumn(name="fromaccount", referencedColumnName="id", unique=false)
*/
private $fromAccount;
/**
* #var Account
*
* #ORM\ManyToOne(targetEntity="Account", cascade={"persist"})
* #ORM\JoinColumn(name="toaccount", referencedColumnName="id", unique=false)
*/
private $toAccount;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="ExpenseType", cascade={"persist"})
* #ORM\JoinColumn(name="expensetype", referencedColumnName="id",
* nullable=true, unique=false)
*/
private $ExpenseType;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="Holder", cascade={"persist"})
* #ORM\JoinColumn(name="holder", referencedColumnName="id", unique=false)
*/
private $orderHolder;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=254)
*/
private $description;
/**
* #var float
*
* #ORM\Column(name="xrate", type="float", nullable=true)
*/
private $xrate = null;
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Account
*
* #param string $account
* #return Movement
*/
public function setAccount($account)
{
$this->Account = $account;
return $this;
}
/**
* Get Account
*
* #return string
*/
public function getAccount()
{
return $this->Account;
}
/**
* Set date
*
* #param \DateTime $date
* #return Movement
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set Type
*
* #param string $type
* #return Movement
*/
public function setType($type)
{
$this->Type = $type;
return $this;
}
/**
* Get Type
*
* #return string
*/
public function getType()
{
return $this->Type;
}
/**
* Set value
*
* #param float $value
* #return Movement
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Get value
*
* #return float
*/
public function getValue()
{
return $this->value;
}
/**
* Set fromAccount
*
* #param string $fromAccount
* #return Movement
*/
public function setFromAccount($fromAccount)
{
$this->fromAccount = $fromAccount;
return $this;
}
/**
* Get fromAccount
*
* #return string
*/
public function getFromAccount()
{
return $this->fromAccount;
}
/**
* Set toAccount
*
* #param string $toAccount
* #return Movement
*/
public function setToAccount($toAccount)
{
$this->toAccount = $toAccount;
return $this;
}
/**
* Get toAccount
*
* #return string
*/
public function getToAccount()
{
return $this->toAccount;
}
/**
* Set ExpenseType
*
* #param string $expenseType
* #return Movement
*/
public function setExpenseType($expenseType)
{
$this->ExpenseType = $expenseType;
return $this;
}
/**
* Get ExpenseType
*
* #return string
*/
public function getExpenseType()
{
return $this->ExpenseType;
}
/**
* Set orderHolder
*
* #param string $orderHolder
* #return Movement
*/
public function setOrderHolder($orderHolder)
{
$this->orderHolder = $orderHolder;
return $this;
}
/**
* Get orderHolder
*
* #return string
*/
public function getOrderHolder()
{
return $this->orderHolder;
}
/**
* Set exchange rate for movement
*
* #param float $xrate
*/
public function setXrate($xrate)
{
$this->xrate = (double)$xrate;
return $this;
}
/**
* Return movement exchange rate
*
* #return float
*/
public function getXrate()
{
return $this->xrate;
}
}
Entity Account
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Account
*
* #ORM\Table(name="account")
*
* #ORM\Entity(repositoryClass="Far\MT\AccountBundle\Entity\AccountRepository")
*/
class Account
{
public function __construct()
{
$this->holders = new ArrayCollection();
$this->pocketAccounts = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=40)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="currency", type="string", length=20)
*/
private $currency;
/**
* #var Far\MT\AccountBundle\Entity\Holder
*
* #ORM\ManyToMany(targetEntity="Holder", inversedBy="Accounts")
* #ORM\JoinTable(name="account_holder",
* joinColumns={#ORM\JoinColumn(name="account_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="holder_id",
* referencedColumnName="id")}
* )
*
*/
private $holders;
/**
* #var Far\MT\AccountBundle\Entity\Account
*
* #ORM\OneToMany(targetEntity="Account", mappedBy="parentAccount")
*/
private $pocketAccounts;
/**
*
* #ORM\ManyToOne(targetEntity="Account", inversedBy="pocketAccounts", cascade={"persist"})
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parentAccount;
/**
* Specifies the account type has string
*
* #var String
*
* #ORM\Column(name="accounttype", type="string", length=40)
*/
private $accountType;
/**
* Total value of available money this should not account money that is
* pending transaction
*
* #var double
*
* #ORM\Column(name="totalavailable", type="float")
*/
private $totalAvailable = 0;
/**
* Total value of accounted money this takes into account money that has
* pending transaction
*
* #var double
*
* #ORM\Column(name="totalaccounted", type="float")
*/
private $totalAccounted = 0;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set code
*
* #param string $code
* #return Account
*/
public function setCode($code)
{
$this->code = str_replace(" ", "", strtoupper(trim($code)));
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set name
*
* #param string $name
* #return Account
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set currency
*
* #param string $currency
* #return Account
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set holders
*
* #param null|Doctrine\Common\Collections\ArrayCollection $holders
* #return Account
*/
public function setHolders($holders)
{
if ($holders === null) {
$this->holders = new ArrayCollection();
} else {
$this->holders = $holders;
}
return $this;
}
/**
* Get holders
*
* #return string
*/
public function getHolders()
{
return $this->holders;
}
/**
*
* Get Pocket accounts
*
* #return \Doctrine\Common\Collections\ArrayCollection()
*/
public function getPocketAccounts()
{
return $this->pocketAccounts;
}
public function setPocketAccounts($PocketAccounts)
{
$this->pocketAccounts = $PocketAccounts;
return $this;
}
/**
* Get Parent Account
*
* #return \Far\MT\AccountBundle\Entity\Account
*
*/
public function getParentAccount()
{
return $this->parentAccount;
}
public function setParentAccount($ParentAccount)
{
$this->parentAccount = ($ParentAccount);
return $this;
}
/**
* does this account has a parent
*
* #return boolean
*/
public function hasParentAccount()
{
return ($this->parentAccount !== null);
}
public function setAccountType($accountType)
{
$this->accountType = $accountType;
return $this;
}
public function getAccountType()
{
return $this->accountType;
}
public function getTotalAccounted()
{
return $this->totalAccounted;
}
public function setTotalAccounted($total)
{
$this->totalAccounted = $total;
return $this;
}
public function getTotalAvailable()
{
return $this->totalAvailable;
}
public function setTotalAvailable($total)
{
$this->totalAvailable = $total;
return $this;
}
public function __toString()
{
return 'Account';
}
}
Please note that what is updated is the Movement entity witch contains the Account in fromAccount and toAccount.
Not knowing the answer he pointed out to me that I did not understand the data_class parameter.
'data_class' => 'Far\MT\AccountBundle\Entity\Account'
18:37 < ocramius> netcrash: no, sorry, can't help since I don't know
what data_class does (not a sf2 form user)
I was missing a Data Transformer, data_class (specifying the Entity was working not sure the reason why...), I placed a DataTransformer and it solved the issue.
See bellow.
use Far\MT\AccountBundle\Form\DataTransformer\AccountToIdTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class Accounts extends AbstractType
{
/**
*
* #var EntityManager
*/
private $em;
private $accountrepo = null;
private $choices = array();
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$transformer = new AccountToIdTransformer($this->em);
$builder->addModelTransformer($transformer);
}
public function setAccountRepository($repo)
{
$this->accountrepo = $repo;
return $this;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'choices' => $this->getChoices(),
'attr' => [
'data-dojo-type' => 'dijit/form/FilteringSelect',
]
]);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'Accounts';
}
public function getChoices()
{
if ( count($this->choices) > 0 ) {
return $this->choices;
}
$this->choices[0] = "";
foreach ($this->accountrepo->findAll() as $account) {
$this->choices[$account->getId()] = $account->getName() . " (" .
$account->getCurrency().") ";
}
return $this->choices;
}
}
And the data transformer:
/**
* This is a transformer for the Account AbstractType
*
* #link http://symfony.com/doc/master/cookbook/form/data_transformers.html
*
* #author andref
*/
class AccountToIdTransformer implements DataTransformerInterface
{
/**
* #var ObjectManager
*/
private $om;
/**
*
* #param ObjectManager $om
*/
public function __construct($om)
{
$this->om = $om;
}
/**
* Transforms an object (issue) to a int (Id).
*
* #param Account|null $account
* #return string
*/
public function transform($account)
{
if (null === $account) {
return "";
}
return $account->getId();
}
/**
* Transforms a int (Id) to an object (Account).
*
* #param int $Id
*
* #return Account|null
*
* #throws TransformationFailedException if object (Account) is not found.
*/
public function reverseTransform($id)
{
if (!$id) {
return null;
}
$Account = $this->om
->getRepository('FarMTAccountBundle:Account')
->findOneBy(array('id' => $id))
;
if (null === $Account) {
throw new TransformationFailedException(sprintf(
'An Account with Id "%s" does not exist!',
$id
));
}
return $Account;
}
}