Error: method __toString() must not throw an exception symfony2 - php

I am working with Symfony2 and I faced with an error:
Error: Method Proxies__CG__\Sprint\SiteBundle\Entity\Task::__toString() must not throw an exception
Here is this this code in my Entity\Task.php:
/**
* #return string
*/
public function __toString()
{
return $this->title;
}
The main problem, that on my local version of this site everything okay and I have this error only on my live site. But they are similar!
Here my Entity\Task.php code:
class Task
{
use TraitDateTimeFields;
use TraitCreatorTimeFields;
use TraitTaskTeamFields;
use TraitTimeTrackFields;
use TraitTagFields;
/**
* #ORM\ManyToMany(targetEntity="Sprint\SiteBundle\Entity\Tag")
* #ORM\JoinTable(
* name="s_task_tags",
* joinColumns={
* #ORM\JoinColumn(name="task_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="tag_id", referencedColumnName="id")
* }
* )
*/
private $tags;
/**
* #ORM\Column(type="integer", name="id")
* #ORM\Id
* #ORM\GeneratedValue
* #Gedmo\TreePathSource
* #var integer
*/
private $id;
/**
* #ORM\Column(type="integer", name="depth", nullable=true)
* #Gedmo\TreeLevel
* #var integer
*/
private $depth;
/**
* #ORM\Column(type="string", name="path", length=255, nullable=true)
* #Gedmo\TreePath
* #var string
*/
private $path;
/** Это группа
* #ORM\Column(type="boolean", name="flag_group")
* #var string
*/
private $flagGroup = false;
/** Архив
*
* #ORM\Column(type="boolean", name="flag_archive")
* #var string
*/
private $flagArchive = false;
/**
* #ORM\Column(type="string", name="number", nullable=false)
* #var string
*/
protected $number = '';
/**
* #ORM\Column(type="string", name="title", nullable=true)
* #var string
*/
protected $title;
/**
* #ORM\Column(type="integer", name="resource")
* #var string
* #deprecated
*/
protected $resource = 0;
/**
* #ORM\Column(type="integer", name="bonus")
* #var string
*/
protected $bonus = 0;
/**
* #ORM\Column(type="integer", name="state")
* #var string
*/
protected $state = TaskState::C_WORKING;
/**
* #ORM\Column(type="integer", name="ttype")
* #var string
*/
protected $type = TaskType::C_INNER;
/** Начало
*
* #ORM\Column(type="datetime", name="start_to", nullable=true)
* #var \DateTime
*/
private $startTo;
/** Дедлайн
*
* #ORM\Column(type="datetime", name="deadline_to", nullable=true)
* #var \DateTime
*/
private $deadlineTo;
/** Срочно
*
* #ORM\Column(type="boolean", name="flag_quicly")
* #var string
*/
private $flagQuickly = false;
/** Формирование бюджета
*
* #ORM\Column(type="boolean", name="flag_budget")
* #var string
*/
private $flagBudget = true;
/**
* #ORM\OneToMany(targetEntity="Sprint\SiteBundle\Entity\EstimateOperatingRow", mappedBy="task", cascade={"detach","persist"}, orphanRemoval=false)
* #var \Doctrine\Common\Collections\ArrayCollection
*/
protected $estimateRows;
/**
* #ORM\ManyToOne(targetEntity="Sprint\SiteBundle\Entity\Project", inversedBy="tasks")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
* #var \Sprint\SiteBundle\Entity\Project
*/
protected $project;
/**
* #ORM\ManyToOne(targetEntity="Sprint\SiteBundle\Entity\Task", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
* #Gedmo\TreeParent
* #var \Sprint\SiteBundle\Entity\Task
*/
protected $parent;
/** Подзадачи
*
* #ORM\OneToMany(targetEntity="Sprint\SiteBundle\Entity\Task", mappedBy="parent", cascade={"all"}, orphanRemoval=true)
* #var \Doctrine\Common\Collections\ArrayCollection
*/
public $children;
/** Задания
*
* #ORM\OneToMany(targetEntity="Sprint\SiteBundle\Entity\TaskAssignment", mappedBy="task", cascade={"all"}, orphanRemoval=true)
* #var \Doctrine\Common\Collections\ArrayCollection
*/
public $assignment;
/** Активность
*
* #ORM\OneToMany(targetEntity="Sprint\SiteBundle\Entity\TaskActivityItem", mappedBy="task", cascade={"all"}, orphanRemoval=true)
* #var \Doctrine\Common\Collections\ArrayCollection
*/
public $activity;
private $activitySummary = [];
protected $operationItems = [];
/**
* Task constructor.
*/
public function __construct()
{
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->activity = new \Doctrine\Common\Collections\ArrayCollection();
$this->auditors = new \Doctrine\Common\Collections\ArrayCollection();
$this->staff = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
$this->estimateRows = new \Doctrine\Common\Collections\ArrayCollection();
$this->assignment = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return string
*/
public function __toString()
{
return $this->title;
}
public function getTreeTitle()
{
return str_pad('', ($this->depth-1)*6*4, ' ', STR_PAD_LEFT) . ($this->flagGroup ? ' ' : ' ') . $this->title;
}
/**
* #return array
*/
public function getPaySummary()
{
$result = [
'total' => 0,
'paid' => 0,
'remains' => 0,
'credit' => 0
];
$now = new \DateTime();
foreach ($this->getOperationItems() as $opt) {
$optSummary = $opt->getSummary();
$result['total'] += $optSummary['total'];
$result['paid'] += $optSummary['paid'];
$result['remains'] += $optSummary['remains'];
if ($opt->getExpectedAt()) {
$df = $now->diff($opt->getExpectedAt());
if ($df->invert) {
$result['credit'] += $optSummary['remains'];
}
}
}
return $result;
}
/**
* #return array
*/
public function getActivitySummary($hourPrice, $forced = false)
{
if ($forced) {
$this->activitySummary = [];
}
if ($this->activitySummary) {
return $this->activitySummary;
}
$result = [
'plannedHours' => 0,
'plannedSmens' => 0,
'plannedPrice' => 0,
'plannedHoursRemains' => 0,
'plannedSmensRemains' => 0,
'plannedPriceRemains' => 0,
'developHours' => 0,
'developSmens' => 0,
'developPrice' => 0,
'developHoursRemains' => 0,
'developSmensRemains' => 0,
'developPriceRemains' => 0,
'innerHours' => 0,
'innerSmens' => 0,
'innerPrice' => 0,
'innerHoursRemains' => 0,
'innerSmensRemains' => 0,
'innerPriceRemains' => 0,
'outherHours' => 0,
'outherSmens' => 0,
'outherPrice' => 0,
'outherHoursRemains' => 0,
'outherSmensRemains' => 0,
'outherPriceRemains' => 0,
'resource' => 0
];
if ($this->flagGroup) {
$childs = $this->getChildren();
if (!$childs->isEmpty()) {
$cnt = $childs->count();
$planSummary = 0.0;
foreach ($childs as $c) {
$planSummary += $c->getPlannedHours();
$cRes = $c->getActivitySummary($hourPrice, $forced);
foreach ($cRes as $k => $v) {
$result[$k] += $v;
}
}
$this->setPlannedHours($planSummary);
}
} else {
foreach ($this->activity as $a) {
switch ($a->getActivity()) {
case TaskActivity::C_DEVELOP :
$result['plannedHours'] += $a->getSpend();
$result['developHours'] += $a->getSpend();
break;
case TaskActivity::C_INNER :
$result['plannedHours'] += $a->getSpend();
$result['innerHours'] += $a->getSpend();
break;
case TaskActivity::C_OUTHER :
$result['plannedHours'] += $a->getSpend();
$result['outherHours'] += $a->getSpend();
break;
}
}
$result['plannedHoursRemains'] = $this->getPlannedHours() - $result['plannedHours'];
$result['developHoursRemains'] = $this->getDevelopHours() - $result['developHours'];
$result['innerHoursRemains'] = $this->getInnerHours() - $result['innerHours'];
$result['outherHoursRemains'] = $this->getOutherHours() - $result['outherHours'];
}
$result['plannedSmens'] = $result['plannedHours'] / 8;
$result['developSmens'] = $result['developHours'] / 8;
$result['innerSmens'] = $result['innerHours'] / 8;
$result['outherSmens'] = $result['outherHours'] / 8;
$result['plannedPrice'] = $result['plannedHours'] * $hourPrice;
$result['developPrice'] = $result['developHours'] * $hourPrice;
$result['innerPrice'] = $result['innerHours'] * $hourPrice;
$result['outherPrice'] = $result['outherHours'] * $hourPrice;
$result['plannedSmensRemains'] = $result['plannedHoursRemains'] / 8;
$result['developSmensRemains'] = $result['developHoursRemains'] / 8;
$result['innerSmensRemains'] = $result['innerHoursRemains'] / 8;
$result['outherSmensRemains'] = $result['outherHoursRemains'] / 8;
$result['plannedPriceRemains'] = $result['plannedHoursRemains'] * $hourPrice;
$result['developPriceRemains'] = $result['developHoursRemains'] * $hourPrice;
$result['innerPriceRemains'] = $result['innerHoursRemains'] * $hourPrice;
$result['outherPriceRemains'] = $result['outherHoursRemains'] * $hourPrice;
if ($this->plannedHours) {
$result['resource'] = round(
($result['developHours'] + $result['innerHours'] + $result['outherHours']) / $this->plannedHours * 100
);
}
$this->activitySummary = $result;
return $this->activitySummary;
}
/**
* #return string
*/
public function getResource()
{
return $this->resource;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* #return bool|\DateInterval
*/
public function getTimeToDeadline()
{
return $this->deadlineTo ? $this->deadlineTo->diff(new \DateTime()) : null;
}
/**
* #return string
*/
public function getFlagQuickly()
{
$interval = $this->getTimeToDeadline();
return ($interval && $interval->invert && $interval->days*24 < 8);
}
/**
* #param string $flagQuickly
*/
public function setFlagQuickly($flagQuickly)
{
$this->flagQuickly = $flagQuickly;
}
/**
* #return string
*/
public function getFlagBudget()
{
return $this->flagBudget;
}
/**
* #param string $flagBudget
*/
public function setFlagBudget($flagBudget)
{
$this->flagBudget = $flagBudget;
}
/**
* #param Project $project
* #return Task
*/
public function setProject($project)
{
$this->project = $project;
return $this;
}
/**
* #return Project
*/
public function getProject()
{
return $this->project;
}
/**
* #return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* #return \Doctrine\Common\Collections\Collection|static
*/
public function getDisplayedChildren()
{
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->where(Criteria::expr()->eq('parent', $this));
return $this->children->matching($criteria);
}
/**
* #param Task $parent
* #return Task
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* #return Task
*/
public function getParent()
{
return $this->parent;
}
/**
* #param \DateTime $startTo
* #return Task
*/
public function setStartTo($startTo)
{
$this->startTo = $startTo;
return $this;
}
/**
* #return \DateTime
*/
public function getStartTo()
{
return $this->startTo;
}
/**
* #param \DateTime $deadlineTo
* #return Task
*/
public function setDeadlineTo($deadlineTo)
{
$this->deadlineTo = $deadlineTo;
return $this;
}
/**
* #return \DateTime
*/
public function getDeadlineTo()
{
return $this->deadlineTo;
}
/**
* #param string $number
* #return Task
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* #return string
*/
public function getNumber()
{
return $this->number;
}
/**
* #param string $resource
* #return Task
*/
public function setResource($resource)
{
$this->resource = $resource;
return $this;
}
/**
* #return mixed
*/
public function getEstimateRows()
{
return $this->estimateRows;
}
/**
* #param $estimateRow
*/
public function addEstimateRow($estimateRow)
{
$estimateRow->setTask($this);
$this->estimateRows->add($estimateRow);
}
/**
* #param $estimateRow
*/
public function removeEstimateRow($estimateRow)
{
$estimateRow->setTask(null);
$this->estimateRows->removeElement($estimateRow);
}
/**
* #param mixed $estimateRows
*/
/*
public function setEstimateRows($estimateRows)
{
$this->estimateRows = $estimateRows;
}
*/
/**
* #return mixed
*/
public function getState()
{
return $this->state;
}
/**
* #param mixed $state
*/
public function setState($state)
{
$this->state = $state;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* #param string $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* #return mixed
*/
public function getBonus()
{
return $this->bonus;
}
/**
* #param mixed $bonus
*/
public function setBonus($bonus)
{
$this->bonus = $bonus;
}
/**
* #return ArrayCollection
*/
public function getActivity()
{
return $this->activity;
}
/**
* #return ArrayCollection
*/
public function getAssignment()
{
return $this->assignment;
}
/**
* #return \Doctrine\Common\Collections\Collection|static
*/
public function getDisplayedActivity()
{
$criteria = Criteria::create();
$criteria->orderBy(['createdAt' => 'DESC']);
$criteria->where(Criteria::expr()->isNull('parent'));
return $this->activity->matching($criteria);
}
/**
* #param $activity
*/
public function addActivity($activity)
{
$this->activity->add($activity);
}
/**
* #param $activity
*/
public function removeActivity($activity)
{
$this->activity->removeElement($activity);
}
/**
* #return mixed
*/
public function getDepth()
{
return $this->depth;
}
/**
* #param mixed $depth
*/
public function setDepth($depth)
{
$this->depth = $depth;
}
/**
* #return mixed
*/
public function getPath()
{
return $this->path;
}
/**
* #param mixed $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* #return string
*/
public function getFlagGroup()
{
return $this->flagGroup;
}
/**
* #param string $flagGroup
*/
public function setFlagGroup($flagGroup)
{
$this->flagGroup = $flagGroup;
}
public function getDirector()
{
return $this->project ? $this->project->getDirector() : $this->director;
}
/**
* #return mixed
*/
public function getFlagArchive()
{
return $this->flagArchive;
}
/**
* #param mixed $flagArchive
*/
public function setFlagArchive($flagArchive)
{
$this->flagArchive = $flagArchive;
}
/**
* #return mixed
*/
public function getOperationItems()
{
return $this->operationItems;
}
/**
* #param mixed $operations
*/
public function setOperationItems($operations)
{
$this->operationItems = $operations;
}
}

You declared $title prop as "nullable". That means, what it can be NULL.
But __toString() must always return the string value.
Try to cast to string return value.
public function __toString()
{
return (string)$this->title;
}

Make sure the function 1. is not called explicitly statically because then $this does not exist and 2. $this->title actually has a value or is casted to string because otherwise it would return null.
/**
* #return string
*/
public function __toString()
{
return (isset($this) && $this->title !== '')
? (string)$this->title
: '';
}

Related

trying to upload a file with synfony 2

i'm trying to upload a file in my database with symfony, I modified my entity, and my form. But when i click on upload a document, i have no error but nothing append (I have no new doc in C:\wamp64\www\myproject\web\upload, and my database field, here support, is null). Here is the code of my entities :
<?php
namespace Main\ConfigBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Invoice
*/
class InvoiceCoach
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $reference_invoice;
/**
* #var string
*/
private $status;
/**
* #var string
*/
private $total = 0;
/**
* #var string
*/
private $tva;
/**
* #var string
*/
private $link;
/**
* #var string
*/
private $paiement_method;
/**
* #var \DateTime
*/
private $date_billing;
/**
* #var \DateTime
*/
private $date_submission;
/**
* #var \DateTime
*/
private $date_creation;
/**
* #var \DateTime
*/
private $date_updated;
/**
* #var string
*/
private $commentaire;
/**
* #var boolean
*/
private $valid_paul = 0;
/**
* #var boolean
*/
private $valid_corinne = 0;
/**
* #var boolean
*/
private $valid_lise = 0;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $invoice;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $element;
/**
* #var \Main\ConfigBundle\Entity\Coach
*/
private $coachs;
/**
* #var File
*/
private $file;
/**
* Constructor
*/
public function __construct()
{
$this->invoice = new \Doctrine\Common\Collections\ArrayCollection();
$this->element = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set referenceInvoice
*
* #param string $referenceInvoice
*
* #return InvoiceCoach
*/
public function setReferenceInvoice($referenceInvoice)
{
$this->reference_invoice = $referenceInvoice;
return $this;
}
/**
* Get referenceInvoice
*
* #return string
*/
public function getReferenceInvoice()
{
return $this->reference_invoice;
}
/**
* Set status
*
* #param string $status
*
* #return InvoiceCoach
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set total
*
* #param string $total
*
* #return InvoiceCoach
*/
public function setTotal($total)
{
$this->total = $total;
return $this;
}
/**
* Get total
*
* #return string
*/
public function getTotal()
{
return $this->total;
}
/**
* Set tva
*
* #param string $tva
*
* #return InvoiceCoach
*/
public function setTva($tva)
{
$this->tva = $tva;
return $this;
}
/**
* Get tva
*
* #return string
*/
public function getTva()
{
return $this->tva;
}
/**
* Set link
*
* #param string $link
*
* #return InvoiceCoach
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set paiementMethod
*
* #param string $paiementMethod
*
* #return InvoiceCoach
*/
public function setPaiementMethod($paiementMethod)
{
$this->paiement_method = $paiementMethod;
return $this;
}
/**
* Get paiementMethod
*
* #return string
*/
public function getPaiementMethod()
{
return $this->paiement_method;
}
/**
* Set dateBilling
*
* #param \DateTime $dateBilling
*
* #return InvoiceCoach
*/
public function setDateBilling($dateBilling)
{
$this->date_billing = $dateBilling;
return $this;
}
/**
* Get dateBilling
*
* #return \DateTime
*/
public function getDateBilling()
{
return $this->date_billing;
}
/**
* Set dateSubmission
*
* #param \DateTime $dateSubmission
*
* #return InvoiceCoach
*/
public function setDateSubmission($dateSubmission)
{
$this->date_submission = $dateSubmission;
return $this;
}
/**
* Get dateSubmission
*
* #return \DateTime
*/
public function getDateSubmission()
{
return $this->date_submission;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
*
* #return InvoiceCoach
*/
public function setDateCreation($dateCreation)
{
$this->date_creation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->date_creation;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
*
* #return InvoiceCoach
*/
public function setDateUpdated($dateUpdated)
{
$this->date_updated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->date_updated;
}
/**
* Set commentaire
*
* #param string $commentaire
*
* #return InvoiceCoach
*/
public function setCommentaire($commentaire)
{
$this->commentaire = $commentaire;
return $this;
}
/**
* Get commentaire
*
* #return string
*/
public function getCommentaire()
{
return $this->commentaire;
}
/**
* Set validPaul
*
* #param boolean $validPaul
*
* #return InvoiceCoach
*/
public function setValidPaul($validPaul)
{
$this->valid_paul = $validPaul;
return $this;
}
/**
* Get validPaul
*
* #return boolean
*/
public function getValidPaul()
{
return $this->valid_paul;
}
/**
* Set validCorinne
*
* #param boolean $validCorinne
*
* #return InvoiceCoach
*/
public function setValidCorinne($validCorinne)
{
$this->valid_corinne = $validCorinne;
return $this;
}
/**
* Get validCorinne
*
* #return boolean
*/
public function getValidCorinne()
{
return $this->valid_corinne;
}
/**
* Set validLise
*
* #param boolean $validLise
*
* #return InvoiceCoach
*/
public function setValidLise($validLise)
{
$this->valid_lise = $validLise;
return $this;
}
/**
* Get validLise
*
* #return boolean
*/
public function getValidLise()
{
return $this->valid_lise;
}
/**
* Add invoice
*
* #param \Main\ConfigBundle\Entity\InvoiceBox $invoice
*
* #return InvoiceCoach
*/
public function addInvoice(\Main\ConfigBundle\Entity\InvoiceBox $invoice)
{
$this->invoice[] = $invoice;
return $this;
}
/**
* Remove invoice
*
* #param \Main\ConfigBundle\Entity\InvoiceBox $invoice
*/
public function removeInvoice(\Main\ConfigBundle\Entity\InvoiceBox $invoice)
{
$this->invoice->removeElement($invoice);
}
/**
* Get invoice
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getInvoice()
{
return $this->invoice;
}
/**
* Add element
*
* #param \Main\ConfigBundle\Entity\InvoiceElement $element
*
* #return InvoiceCoach
*/
public function addElement(\Main\ConfigBundle\Entity\InvoiceElement $element)
{
$this->element[] = $element;
return $this;
}
/**
* Remove element
*
* #param \Main\ConfigBundle\Entity\InvoiceElement $element
*/
public function removeElement(\Main\ConfigBundle\Entity\InvoiceElement $element)
{
$this->element->removeElement($element);
}
/**
* Get element
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getElement()
{
return $this->element;
}
/**
* Set coachs
*
* #param \Main\ConfigBundle\Entity\Coach $coachs
*
* #return InvoiceCoach
*/
public function setCoachs(\Main\ConfigBundle\Entity\Coach $coachs = null)
{
$this->coachs = $coachs;
return $this;
}
/**
* Get coachs
*
* #return \Main\ConfigBundle\Entity\Coach
*/
public function getCoachs()
{
return $this->coachs;
}
/**
* #var string
*/
private $support;
/**
* Set support
*
* #param string $support
*
* #return InvoiceCoach
*/
public function setSupport($support)
{
$this->support = $support;
return $this;
}
/**
* Get support
*
* #return string
*/
public function getSupport()
{
return $this->support;
}
/**
* Set file
*
* #param File $file
* #return InvoiceCoach
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return File
*/
public function getFile()
{
return $this->file;
}
// File Upload Method
public function getAbsolutePath()
{
return null === $this->support ? null : $this->getUploadRootDir().'/'.$this->support;
}
public function getPath()
{
return null === $this->support ? null : $this->getUploadDir().'/'.$this->support;
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
return 'upload';
}
// Doctrine Specific Method
public function __persist()
{
if($this->file !== null)
$this->support = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
}
public function __postPersist()
{
if($this->file === null)
return;
$this->file->move($this->getUploadRootDir(), $this->support);
unset($this->file);
$this->file = null;
}
public function __flush()
{
if($this->file === null)
return;
$this->__remove();
$this->__persist();
$this->__postPersist();
}
public function __remove()
{
if($file = $this->getAbsolutePath())
if(file_exists($file))
unlink($file);
}
}
THX a lot
edit : here is the code of my controller (when the form is created) and where I call it on twig :
$em = $this->getDoctrine()->getManager();
$invoice = $em->getRepository("MainConfigBundle:InvoiceCoach")->find($id);
$formUpload = $this->createForm('invoicesupport', $invoice)
->add('save', 'submit', array('label' => 'Enregistrer') );
if($request->getMethod() == "POST"){
$formUpload->handleRequest($request);
if($formUpload->isValid()){
$em->persist($invoice);
$em->flush();
}
return $this->redirect($this->generateUrl('coach_paid_edit', array('id' => $id) ));
}
twig :
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Upload facture</h5>
</div>
<div class="modal-body">
{{ form_start(form, {'attr': {'novalidate': 'novalidate', 'data-parsley-validate':'data-parsley-validate'}}) }}
{{ form_row(formUpload.file) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
{{ form_row(formUpload.save) }}
{{ form_end(form) }}
</div>
</div>
First and most important - did you test that "Doctrine Specific Method" are firing up ?. My guess is that they not firing up (honestly i see first time approach like this - and i don't know why should it work)
Even if - i think that approach is bad , this code should be moved to event listeners/subscribed . It shouldn't be in entity file.
Look at http://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
Here you have link to my old upload solution with Trait connected to entity
https://gist.github.com/poznet/e3955a48fea01d8640dafbd966c53a83

Error with mass flush objects doctrine

This causes an error:
$em = $this->getDoctrine()->getManager();
$courses = $em->getRepository(Course::class)->findBy(['id' => $ids]);
foreach ($courses as $course) {
$data = $form->getData();
$course->setProperties($data);
$em->persist($course);
}
$em->flush();
The followin error is thown:
Type error:
Argument 3 passed to Doctrine\ORM\Event\PreUpdateEventArgs::
__construct() must be of the type array, null given, called in:
/var/www/bib/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 1064
But when I insert $em->flush(); In a cycle - everything works.
What wrong?
Course entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use CoreBundle\Entity\GuidTrait;
use CoreBundle\Entity\Typo3Trait;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
use CoreBundle\Entity\LoggableTrait;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\CourseRepository")
* #ORM\Table(name="courses")
* #ORM\HasLifecycleCallbacks()
*/
class Course
{
use GuidTrait, Typo3Trait, Timestampable, LoggableTrait;
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
/**
* #ORM\Column(type="string", length=150, nullable=true)
*/
protected $title;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string")
*/
protected $code;
/**
* #Assert\NotBlank()
* #ORM\Column(name="`order`", type="integer")
*/
protected $order;
/**
* #Assert\NotBlank()
* #ORM\Column(type="smallint")
*/
protected $status;
/**
* #Assert\NotBlank()
* #Assert\DateTime()
* #ORM\Column(type="datetime", nullable=false)
*/
protected $date;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $enrolmentDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $durationDetails;
/**
* #Assert\NotBlank()
* #ORM\Column(type="text", nullable=false)
*/
protected $timetable;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactName;
/**
* #Assert\NotBlank()
* #Assert\Email
* #ORM\Column(type="string", nullable=false)
*/
protected $contactEmail;
/**
* #Assert\NotBlank()
* #ORM\Column(type="string", nullable=false)
*/
protected $contactPhone;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $contactFax;
/**
* #Assert\NotBlank()
* #Assert\Type(type="float")
* #Assert\GreaterThanOrEqual(0)
*
* #ORM\Column(type="decimal", precision=8, scale=2, nullable=false)
*/
protected $price;
/**
* #Assert\NotBlank()
* #Assert\GreaterThanOrEqual(0)
* #Assert\Type(type="integer")
*
* #ORM\Column(type="integer", nullable=false)
*/
protected $availability;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $courseNotes;
/**
* #ORM\ManyToOne(targetEntity="Centre", inversedBy="courses")
* #ORM\JoinColumn(name="centre_id", referencedColumnName="uid")
*/
protected $centre;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Qualification", inversedBy="courses")
* #ORM\JoinColumn(name="qualification_id", referencedColumnName="uid",onDelete="CASCADE")
*/
protected $qualification;
/**
* #Assert\NotBlank()
* #ORM\ManyToOne(targetEntity="Venue", inversedBy="courses")
* #ORM\JoinColumn(name="venue_id", referencedColumnName="uid")
*/
protected $venue;
/**
* #ORM\OneToMany(targetEntity="Booking", mappedBy="course", cascade={"remove"})
*/
protected $bookings;
/**
* #ORM\Column(type="string", nullable=false)
*/
protected $reference;
public function __construct()
{
$this->status = self::STATUS_ACTIVE;
$this->code = 'CODE';
$this->order = 1;
}
/**
* #ORM\PreFlush
*/
public function updateReference()
{
$q = $this->getQualification()->getCode();
$c = $this->getCentre()->getCode();
$v = $this->getVenue()->getCode();
$d = $this->getDate()->format('d/m/Y');
$this->setReference("$q - $c - $v - $d");
}
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param $title
* #return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* #return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* #param $code
* #return $this
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* #return mixed
*/
public function getOrder()
{
return $this->order;
}
/**
* #param $order
* #return $this
*/
public function setOrder($order)
{
$this->order = $order;
return $this;
}
/**
* #return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* #param $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param $date
* #return $this
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* #return mixed
*/
public function getEnrolmentDetails()
{
return $this->enrolmentDetails;
}
/**
* #param $enrolmentDetails
* #return $this
*/
public function setEnrolmentDetails($enrolmentDetails)
{
$this->enrolmentDetails = $enrolmentDetails;
return $this;
}
/**
* #return mixed
*/
public function getDurationDetails()
{
return $this->durationDetails;
}
/**
* #param $durationDetails
* #return $this
*/
public function setDurationDetails($durationDetails)
{
$this->durationDetails = $durationDetails;
return $this;
}
/**
* #return mixed
*/
public function getTimetable()
{
return $this->timetable;
}
/**
* #param $timetable
* #return $this
*/
public function setTimetable($timetable)
{
$this->timetable = $timetable;
return $this;
}
/**
* #return mixed
*/
public function getContactName()
{
return $this->contactName;
}
/**
* #param $contactName
* #return $this
*/
public function setContactName($contactName)
{
$this->contactName = $contactName;
return $this;
}
/**
* #return mixed
*/
public function getContactEmail()
{
return $this->contactEmail;
}
/**
* #param $contactEmail
* #return $this
*/
public function setContactEmail($contactEmail)
{
$this->contactEmail = $contactEmail;
return $this;
}
/**
* #return mixed
*/
public function getContactPhone()
{
return $this->contactPhone;
}
/**
* #param $contactPhone
* #return $this
*/
public function setContactPhone($contactPhone)
{
$this->contactPhone = $contactPhone;
return $this;
}
/**
* #return mixed
*/
public function getContactFax()
{
return $this->contactFax;
}
/**
* #param $contactFax
* #return $this
*/
public function setContactFax($contactFax)
{
$this->contactFax = $contactFax;
return $this;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param $price
* #return $this
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* #return mixed
*/
public function getAvailability()
{
return $this->availability;
}
/**
* #param $availability
* #return $this
*/
public function setAvailability($availability)
{
$this->availability = $availability;
return $this;
}
/**
* #return mixed
*/
public function getCourseNotes()
{
return $this->courseNotes;
}
/**
* #param $courseNotes
* #return $this
*/
public function setCourseNotes($courseNotes)
{
$this->courseNotes = $courseNotes;
return $this;
}
/**
* #return mixed
*/
public function getCentre()
{
return $this->centre;
}
/**
* #param $centre
* #return $this
*/
public function setCentre($centre)
{
$this->centre = $centre;
return $this;
}
/**
* #return mixed
*/
public function getQualification()
{
return $this->qualification;
}
/**
* #param $qualification
* #return $this
*/
public function setQualification($qualification)
{
$this->qualification = $qualification;
return $this;
}
/**
* #return mixed
*/
public function getVenue()
{
return $this->venue;
}
/**
* #param $venue
* #return $this
*/
public function setVenue($venue)
{
$this->venue = $venue;
return $this;
}
/**
* #return mixed
*/
public function getReference()
{
return $this->reference;
}
/**
* #param $reference
* #return $this
*/
public function setReference($reference)
{
$this->reference = $reference;
return $this;
}
/**
* #return mixed
*/
public function getBookings()
{
return $this->bookings;
}
/**
* #param mixed $bookings
*/
public function setBookings($bookings)
{
$this->bookings = $bookings;
}
public function getVat( $amount = 0 )
{
if (empty($amount)) {
return round( $this->price * $this->centre->getVat()->getRate()/100, 2 );
} else {
return round( $amount * $this->centre->getVat()->getRate()/100, 2 );
}
}
public function setProperties(Course $course)
{
foreach ($this as $key=>$value) {
if ($course->$key) {
$this->$key = $course->$key;
}
}
}
}
There is nothing supernatural in this entity.
Does anyone have an answer to the question I asked?
There are many issues in Symfony and Doctrine when you execute the flush() method. For example, calling flush() inside a Doctrine listener is not a supported Doctrine usage. it means you are trying to nest several flushes inside each other, which can indeed break the unit of work.
There is a really complete examplample in this StackOverflow Answer, but I think it maybe not be enaugh to understand your problem, so if you want you can check all the posible scenarios where flush should fail here:
https://github.com/doctrine/doctrine2/issues/4004

Symfony2 + Doctrine2 not updating in my database

I have an api in symfony2, in which adding and deleting items is not issue, however, updating doesn't throw me any errors however the relevent row in my database does not get updated!
My Controller method:
/*
* #Route("/complete/uid/{storeUid}",
* name = "media_complete"
* )
*
* #Method({"GET"})
*
* #param String $storeUid - the uid for the store that has completed downloading
*
* #return Response
*/
public function downloadCompleteAction($storeUid)
{
$response = $this->getNewJsonResponse();
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository("SimplySmartUHDProBundle:Machine");
try {
//get the machine from the db
$machine = $repo->findOneBy(array(
"uid" => $storeUid
));
//set it as download completed
$machine->setStatus(Machine::STATUS_DOWNLOAD_COMPLETE);
$em->persist($machine);
$em->flush();
$response->setStatusCode(200);
} catch (\Exception $e) {
//if there is an error, catch the exception set the status to 500 and return json with the exception error
$error = array("message" => $e->getMessage());
$response->setContent(json_encode($error));
$response->setStatusCode(500);
}
return $response;
}
My Entity:
namespace SimplySmart\UHDProBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use SimplySmart\UHDProBundle\Entity\Store;
/**
* Machine
*
* #ORM\Table(name="Machines", uniqueConstraints={#ORM\UniqueConstraint(name="UID", columns={"UID"})})
* #ORM\Entity
*/
class Machine
{
const STATUS_NO_FEED = 0;
const STATUS_REQUIRES_DOWNLOAD = 1;
const STATUS_DOWNLOAD_IN_PROGRESS = 2;
const STATUS_DOWNLOAD_COMPLETE = 3;
/**
* Array of available statuses
*
* #var array
*/
static public $statuses = array(
self::STATUS_NO_FEED,
self::STATUS_REQUIRES_DOWNLOAD,
self::STATUS_DOWNLOAD_IN_PROGRESS,
self::STATUS_DOWNLOAD_COMPLETE
);
/**
* #var string
*
* #ORM\Column(name="UID", type="string", length=50, nullable=false)
*/
private $uid;
/**
* #var string
*
* #ORM\Column(name="StoreCode", type="string", length=10, nullable=false)
*/
private $storecode;
/**
* #var string
*
* #ORM\Column(name="Description", type="string", length=100, nullable=true)
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="Status", type="boolean", nullable=false)
*/
private $status;
/**
* #var boolean
*
* #ORM\Column(name="OnlineStatus", type="boolean", nullable=false)
*/
private $onlinestatus;
/**
* #var string
*
* #ORM\Column(name="Version", type="string", length=10, nullable=false)
*/
private $version;
/**
* #var \DateTime
*
* #ORM\Column(name="Timestamp", type="datetime", nullable=false)
*/
private $timestamp;
/**
* #ORM\ManyToOne(targetEntity="SimplySmart\UHDProBundle\Entity\Store", inversedBy="machines")
* #ORM\JoinColumn(name="StoreCode", referencedColumnName="Code")
*/
protected $store;
/**
* #ORM\ManyToMany(targetEntity="SimplySmart\UHDProBundle\Entity\Feed", inversedBy="machines")
* #ORM\JoinTable(joinColumns={#ORM\JoinColumn(name="machine_id", referencedColumnName="MachID")},
* inverseJoinColumns={#ORM\JoinColumn(name="feed_id", referencedColumnName="FeedID")}
* )
*
*/
protected $feeds;
/**
* #var integer
*
* #ORM\Column(name="MachID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $machid;
/**
*
*/
public function __construct()
{
$this->feeds = new ArrayCollection();
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getFeedtype()
{
return $this->feedtype;
}
/**
* #param string $feedtype
*
* #return $this
*/
public function setFeedtype($feedtype)
{
$this->feedtype = $feedtype;
return $this;
}
/**
* #return int
*/
public function getMachid()
{
return $this->machid;
}
/**
* #param int $machid
*
* #return $this
*/
public function setMachid($machid)
{
$this->machid = $machid;
return $this;
}
/**
* #return boolean
*/
public function isOnlinestatus()
{
return $this->onlinestatus;
}
/**
* #param boolean $onlinestatus
*
* #return $this
*/
public function setOnlinestatus($onlinestatus)
{
$this->onlinestatus = $onlinestatus;
return $this;
}
/**
* #return boolean
*/
public function isStatus()
{
return $this->status;
}
/**
* #param boolean $status
*
* #throws \Exception if invalid status is given
*
* #return $this
*/
public function setStatus($status)
{
if (in_array($status, self::$statuses)) {
$this->status = $status;
} else {
throw new \Exception("invalid status given");
}
return $this;
}
/**
* #return string
*/
public function getStorecode()
{
return $this->storecode;
}
/**
* #param string $storecode
*
* #return $this
*/
public function setStorecode($storecode)
{
$this->storecode = $storecode;
return $this;
}
/**
* #return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* #param \DateTime $timestamp
*
* #return $this
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
return $this;
}
/**
* #return string
*/
public function getUid()
{
return $this->uid;
}
/**
* #param string $uid
*
* #return $this
*/
public function setUid($uid)
{
$this->uid = $uid;
return $this;
}
/**
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* #param string $version
*
* #return $this
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
/**
* Get onlinestatus
*
* #return boolean
*/
public function getOnlinestatus()
{
return $this->onlinestatus;
}
/**
* Set store
*
* #param \SimplySmart\UHDProBundle\Entity\Store $store
* #return Machine
*/
public function setStore(\SimplySmart\UHDProBundle\Entity\Store $store = null)
{
$this->store = $store;
return $this;
}
/**
* Get store
*
* #return \SimplySmart\UHDProBundle\Entity\Store
*/
public function getStore()
{
return $this->store;
}
/**
* Method to generate and set a new UID
*
* #return $this
*/
public function generateNewUid()
{
$date = new \DateTime("UTC");
$uid = "U";
$uid .= $date->format("U");
$uid .= 'R'.rand(0,100);
$this->setUid($uid);
return $this;
}
/**
* Add feeds
*
* #param \SimplySmart\UHDProBundle\Entity\Feed $feeds
* #return Machine
*/
public function addFeed(\SimplySmart\UHDProBundle\Entity\Feed $feeds)
{
$this->feeds[] = $feeds;
return $this;
}
/**
* Remove feeds
*
* #param \SimplySmart\UHDProBundle\Entity\Feed $feeds
*/
public function removeFeed(\SimplySmart\UHDProBundle\Entity\Feed $feeds)
{
$this->feeds->removeElement($feeds);
}
/**
* Get feeds
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFeeds()
{
return $this->feeds;
}
}
I am fully aware that when updating an entity I shouldn't need to use $em->persist($machine), however removing this doesn't seem to make any difference.
The part that is really grinding my gears, is that when I go on the profiler, it appears as it is ran all the queries as expected!
Just realised that I've been a complete idiot and my issue is that status is set as a boolean field in my entity, so it was updating, but always setting it as 1!

Doctrine 2 perform insert, update on entity locally but fails without error on staging

I have an entity called DoerTrip
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Doer Trip
*
* #ORM\Table(name="doer_trip")
* #ORM\Entity
*/
class DoerTrip extends AbstractEntity
{
const STATUS_PUBLISHED = 1;
const STATUS_UNPUBLISHED = 0;
/**
* #var integer
*
* #ORM\Column(name="`id`", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var \Application\Entity\Doer
*
* #ORM\ManyToOne(targetEntity="Doer")
* #ORM\JoinColumn(name="`doer_id`", referencedColumnName="id")
*/
protected $doer; // inversedBy="trips"
/**
* #var \Application\Entity\Trip
*
* #ORM\ManyToOne(targetEntity="Trip")
* #ORM\JoinColumn(name="`trip_id`", referencedColumnName="id")
*/
protected $trip; //inversedBy="doers"
/**
* #var bool
*
* #ORM\Column(name="`published`", type="boolean")
*/
protected $published;
/**
* #var string
*
* #ORM\Column(name="`comment`", type="text")
*/
protected $comment;
/**
* #var integer
*
* #ORM\Column(name="`target_sum`", type="integer")
*/
protected $targetSum;
public function __construct()
{
$this->published = false;
}
/**
* #param string $comment
* #return $this
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* #param \Application\Entity\Doer $doer
* #return $this
*/
public function setDoer(Doer $doer)
{
$this->doer = $doer;
return $this;
}
/**
* #return \Application\Entity\Doer
*/
public function getDoer()
{
return $this->doer;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param boolean $published
* #return $this
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* #return boolean
*/
public function getPublished()
{
return $this->published;
}
/**
* #param \Application\Entity\Trip $trip
* #return $this
*/
public function setTrip(Trip $trip)
{
$this->trip = $trip;
return $this;
}
/**
* #return \Application\Entity\Trip
*/
public function getTrip()
{
return $this->trip;
}
/**
* #param int $targetSum
* #return $this
*/
public function setTargetSum($targetSum)
{
$this->targetSum = $targetSum;
return $this;
}
/**
* #return int
*/
public function getTargetSum()
{
return (null !== $this->targetSum) ? $this->targetSum : $this->getTrip()->getTargetAmount();
}
}
here Trip Entity:
namespace Application\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Zend\Validator\IsInstanceOf;
/**
* Trip
*
* #ORM\Table(name="trip")
* #ORM\Entity
*/
class Trip extends AbstractEntity
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #var Collection
*
* #ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
* #ORM\JoinTable(name="trip_media",
* joinColumns={#ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
* )
*/
protected $media;
/**
* #var \Application\Entity\Media
*
* #ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
*/
protected $mainMedia;
/**
* #var string
*
* #ORM\Column(name="api_key", type="string", length=255)
*/
protected $apiKey;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=255, nullable=true)
*/
protected $country;
/**
* #var \DateTime
*
* #ORM\Column(name="departure_date", type="date", nullable=true)
*/
protected $departureDate;
/**
* #var \DateTime
*
* #ORM\Column(name="due_date", type="date", nullable=true)
*/
protected $dueDate;
/**
* #var \DateTime
*
* #ORM\Column(name="return_date", type="date", nullable=true)
*/
protected $returnDate;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="target_amount", type="integer")
*/
protected $targetAmount;
/**
* #var Collection
*
* #ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
*/
protected $doers;
/**
* #var Organization
*
* #ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
*/
protected $organization;
/**
* #var Cause
*
* #ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
* #ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $cause;
/**
* #var integer
*
* #ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
*/
protected $status;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var Transaction
*
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
*/
protected $transactions;
/**
* #param Organization $organization
* #return $this
*/
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
return $this;
}
/**
* #return Organization
*/
public function getOrganization()
{
return $this->organization;
}
public function __construct()
{
$this->doers = new ArrayCollection();
$this->media = new ArrayCollection();
$this->status = self::STATUS_ACTIVE;
$this->transactions = new ArrayCollection();
$this->targetAmount = 0;
$this->description = '';
}
/**
* #param string $apiKey
* #return $this
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
return $this;
}
/**
* #return string
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param string $country
* #return $this
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* #param string $description
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param \DateTime $dueDate
* #return $this
*/
public function setDueDate(\DateTime $dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \DateTime $departureDate
* #return $this
*/
public function setDepartureDate(\DateTime $departureDate)
{
$this->departureDate = $departureDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDepartureDate()
{
return $this->departureDate;
}
/**
* #param string $targetAmount
* #return $this
*/
public function setTargetAmount($targetAmount)
{
$this->targetAmount = $targetAmount;
return $this;
}
/**
* #return string
*/
public function getTargetAmount()
{
return $this->targetAmount;
}
/**
* #param string $name
* #return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param int $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* #param \Application\Entity\Cause $cause
* #return $this
*/
public function setCause($cause)
{
$this->cause = $cause;
return $this;
}
/**
* #return \Application\Entity\Cause
*/
public function getCause()
{
return $this->cause;
}
/**
* #param \Doctrine\Common\Collections\Collection $media
* #return $this
*/
public function setMedia($media)
{
$this->media = $media;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getMedia()
{
return $this->media;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function addDoer(DoerTrip $doer)
{
$this->doers->add($doer);
$doer->setTrip($this);
return $this;
}
/**
* #param Collection $doers
* #return $this
*/
public function setDoers(Collection $doers)
{
$this->doers = $doers;
return $this;
}
/**
* #return Collection
*/
public function getDoers()
{
return $this->doers;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function removeDoer(DoerTrip $doer)
{
$this->doers->removeElement($doer);
return $this;
}
/**
* #param \Doctrine\Common\Collections\Collection $transactions
* #return $this
*/
public function setTransactions($transactions)
{
$this->transactions = $transactions;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getTransactions()
{
return $this->transactions;
}
/**
* #param array $data
* #return $this
*/
public function populate(array $data)
{
if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
$data['departureDate'] = new \DateTime($data['departureDate']);
}
if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
$data['dueDate'] = new \DateTime($data['dueDate']);
}
if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
$data['returnDate'] = new \DateTime($data['returnDate']);
}
parent::populate($data);
return $this;
}
/**
* #param \DateTime $returnDate
* #return $this
*/
public function setReturnDate(\DateTime $returnDate)
{
$this->returnDate = $returnDate;
return $this;
}
/**
* #return \DateTime
*/
public function getReturnDate()
{
return $this->returnDate;
}
/**
* #param \Application\Entity\Media $mainMedia
* #return $this
*/
public function setMainMedia($mainMedia)
{
$this->mainMedia = $mainMedia;
return $this;
}
/**
* #return \Application\Entity\Media
*/
public function getMainMedia()
{
return $this->mainMedia;
}
/**
* #param Media $media
* #return bool
*/
public function hasMedia(Media $media)
{
return $this->getMedia()->contains($media);
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function addMedia(Media $media)
{
$this->media->add($media);
return $this;
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function removeMedia(Media $media)
{
$this->media->removeElement($media);
return $this;
}
}
Here is Doer Entity
namespace Application\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Zend\Validator\IsInstanceOf;
/**
* Trip
*
* #ORM\Table(name="trip")
* #ORM\Entity
*/
class Trip extends AbstractEntity
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_BANNED = 'banned';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/**
* #var Collection
*
* #ORM\ManyToMany(targetEntity="Media", cascade={"remove"}, orphanRemoval=true)
* #ORM\JoinTable(name="trip_media",
* joinColumns={#ORM\JoinColumn(name="trip_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="file_id", referencedColumnName="id", unique=true)}
* )
*/
protected $media;
/**
* #var \Application\Entity\Media
*
* #ORM\OneToOne(targetEntity="Media", mappedBy="trip", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="main_media_id", referencedColumnName="id")
*/
protected $mainMedia;
/**
* #var string
*
* #ORM\Column(name="api_key", type="string", length=255)
*/
protected $apiKey;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=255, nullable=true)
*/
protected $country;
/**
* #var \DateTime
*
* #ORM\Column(name="departure_date", type="date", nullable=true)
*/
protected $departureDate;
/**
* #var \DateTime
*
* #ORM\Column(name="due_date", type="date", nullable=true)
*/
protected $dueDate;
/**
* #var \DateTime
*
* #ORM\Column(name="return_date", type="date", nullable=true)
*/
protected $returnDate;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* #var string
*
* #ORM\Column(name="target_amount", type="integer")
*/
protected $targetAmount;
/**
* #var Collection
*
* #ORM\OneToMany(targetEntity="DoerTrip", mappedBy="trip", cascade={"persist","remove"}, orphanRemoval=true)
*/
protected $doers;
/**
* #var Organization
*
* #ORM\ManyToOne(targetEntity="Organization", inversedBy="trips")
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
*/
protected $organization;
/**
* #var Cause
*
* #ORM\OneToOne(targetEntity="Cause", inversedBy="trips")
* #ORM\JoinColumn(name="cause_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $cause;
/**
* #var integer
*
* #ORM\Column(name="status", type="string" ,columnDefinition="ENUM('active', 'inactive', 'banned')")
*/
protected $status;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var Transaction
*
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="trip", cascade={"remove"}, orphanRemoval=true)
*/
protected $transactions;
/**
* #param Organization $organization
* #return $this
*/
public function setOrganization(Organization $organization)
{
$this->organization = $organization;
return $this;
}
/**
* #return Organization
*/
public function getOrganization()
{
return $this->organization;
}
public function __construct()
{
$this->doers = new ArrayCollection();
$this->media = new ArrayCollection();
$this->status = self::STATUS_ACTIVE;
$this->transactions = new ArrayCollection();
$this->targetAmount = 0;
$this->description = '';
}
/**
* #param string $apiKey
* #return $this
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
return $this;
}
/**
* #return string
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param string $country
* #return $this
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* #param string $description
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param \DateTime $dueDate
* #return $this
*/
public function setDueDate(\DateTime $dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* #param int $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param \DateTime $departureDate
* #return $this
*/
public function setDepartureDate(\DateTime $departureDate)
{
$this->departureDate = $departureDate;
return $this;
}
/**
* #return \DateTime
*/
public function getDepartureDate()
{
return $this->departureDate;
}
/**
* #param string $targetAmount
* #return $this
*/
public function setTargetAmount($targetAmount)
{
$this->targetAmount = $targetAmount;
return $this;
}
/**
* #return string
*/
public function getTargetAmount()
{
return $this->targetAmount;
}
/**
* #param string $name
* #return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param int $status
* #return $this
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* #param \Application\Entity\Cause $cause
* #return $this
*/
public function setCause($cause)
{
$this->cause = $cause;
return $this;
}
/**
* #return \Application\Entity\Cause
*/
public function getCause()
{
return $this->cause;
}
/**
* #param \Doctrine\Common\Collections\Collection $media
* #return $this
*/
public function setMedia($media)
{
$this->media = $media;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getMedia()
{
return $this->media;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function addDoer(DoerTrip $doer)
{
$this->doers->add($doer);
$doer->setTrip($this);
return $this;
}
/**
* #param Collection $doers
* #return $this
*/
public function setDoers(Collection $doers)
{
$this->doers = $doers;
return $this;
}
/**
* #return Collection
*/
public function getDoers()
{
return $this->doers;
}
/**
* #param \Application\Entity\DoerTrip $doer
* #return $this
*/
public function removeDoer(DoerTrip $doer)
{
$this->doers->removeElement($doer);
return $this;
}
/**
* #param \Doctrine\Common\Collections\Collection $transactions
* #return $this
*/
public function setTransactions($transactions)
{
$this->transactions = $transactions;
return $this;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getTransactions()
{
return $this->transactions;
}
/**
* #param array $data
* #return $this
*/
public function populate(array $data)
{
if (!empty($data['departureDate']) && !$data['departureDate'] instanceof \DateTime) {
$data['departureDate'] = new \DateTime($data['departureDate']);
}
if (!empty($data['dueDate']) && !$data['dueDate'] instanceof \DateTime) {
$data['dueDate'] = new \DateTime($data['dueDate']);
}
if (!empty($data['returnDate']) && !$data['returnDate'] instanceof \DateTime) {
$data['returnDate'] = new \DateTime($data['returnDate']);
}
parent::populate($data);
return $this;
}
/**
* #param \DateTime $returnDate
* #return $this
*/
public function setReturnDate(\DateTime $returnDate)
{
$this->returnDate = $returnDate;
return $this;
}
/**
* #return \DateTime
*/
public function getReturnDate()
{
return $this->returnDate;
}
/**
* #param \Application\Entity\Media $mainMedia
* #return $this
*/
public function setMainMedia($mainMedia)
{
$this->mainMedia = $mainMedia;
return $this;
}
/**
* #return \Application\Entity\Media
*/
public function getMainMedia()
{
return $this->mainMedia;
}
/**
* #param Media $media
* #return bool
*/
public function hasMedia(Media $media)
{
return $this->getMedia()->contains($media);
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function addMedia(Media $media)
{
$this->media->add($media);
return $this;
}
/**
* #param \Application\Entity\Media $media
* #return $this
*/
public function removeMedia(Media $media)
{
$this->media->removeElement($media);
return $this;
}
}
I perform this sample of code:
$doerTrip = new DoerTrip();
$doerTrip->setDoer($doer)->setTrip($trip);
$em->persist($doerTrip);
$em->flush();
locally it works (on Windows). But on staging (Ubuntu) new record is not created and I don't get any errors. Update of the entity DoerTrip on staging doesn't work too.
If I perform insert with the help of connection something like this
$stmt = $conn->prepare('INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)');
$stmt->bindParam(1, $param);
...
everything works fine.
When using ORM in SQL Logger I can see
START TRANSACTION;
INSERT INTO doer_trip (...) VALUES (?,?,?,?,?)
COMMIT;
but new record is not created on staging.
locally everything works fine.
I don't know maybe it depends on MySQL configuration.
I have no idea.
Here my doer_trip table
CREATE TABLE `doer_trip` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`doer_id` INT(11) NOT NULL,
`trip_id` INT(11) UNSIGNED NOT NULL,
`published` INT(1) UNSIGNED NOT NULL DEFAULT '0',
`comment` TEXT NULL,
`target_sum` INT(10) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `doer_id` (`doer_id`),
INDEX `trip_id` (`trip_id`),
UNIQUE INDEX `doer_iduniq` (`doer_id`, `trip_id`),
CONSTRAINT `FK_doer_trip_trip` FOREIGN KEY (`trip_id`) REFERENCES `trip` (`id`),
CONSTRAINT `FK_doer_trip_doer` FOREIGN KEY (`doer_id`) REFERENCES `doer` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=41
The problem was in
/**
* #var bool
*
* #ORM\Column(name="`published`", type="boolean")
*/
protected $published;
If I set type to integer like this
/**
* #var integer
*
* #ORM\Column(name="`published`", type="integer")
*/
protected $published;
Everything work fine. But why it works fine on my local environment???

AbstractType Proxies\__CG__\Far\MT\AccountBundle\Entity\Account could not be converted to int in

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;
}
}

Categories