Warning: get_class() expects parameter 1 to be object, integer given - php

I don't know what's the problem when i want to insert some data to the database it show this error
<?php
namespace ArticleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ArticleRate
*
* #ORM\Table(name="article_rate")
* #ORM\Entity(repositoryClass="ArticleBundle\Repository\ArticleRateRepository")
*/
class ArticleRate
{
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var int
*
* #ORM\Id
* #ORM\OneToOne(targetEntity="Article")
* #ORM\JoinColumn(name="article_id", referencedColumnName="id")
*/
private $idArticle;
/**
* #var int
* #ORM\Id
* #ORM\OneToOne(targetEntity="GUBundle\Entity\Utilisateur")
*
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $idUser;
public function __construct()
{
$this->date = new \DateTime();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return ArticleRate
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set idArticle
*
* #param integer $idArticle
*
* #return ArticleRate
*/
public function setIdArticle($idArticle)
{
$this->idArticle = $idArticle;
return $this;
}
/**
* Get idArticle
*
* #return int
*/
public function getIdArticle()
{
return $this->idArticle;
}
/**
* Set idUser
*
* #param string $idUser
*
* #return ArticleRate
*/
public function setIdUser($idUser)
{
$this->idUser = $idUser;
return $this;
}
/**
* Get idUser
*
* #return string
*/
public function getIdUser()
{
return $this->idUser;
}
}
/**
* #param $id
* #return JsonResponse
*/
public function AimeArticlesAction($id)
{
$em = $this->getDoctrine()->getManager();
$article=new ArticleRate();
$article->setIdArticle(1);
$article->setIdUser(1);
dump($article);
$article=(object) $article;
$em->persist($article);
$em->flush();
return new JsonResponse("yes");
}
}

The error seems clear to me: you give an integer (1) and doctrine expects an object.
Doctrine is managing object. These mean you should use $article->getUser()->getId() instead of $article->getUserId().
For your specific probleme: those 2 functions expect objects
$article->setIdArticle(1);
$article->setIdUser(1);
That's why you should name those method Article And User.
You can give them an proxy object by using getReference
$article->setUser($this->getDoctrine()->getManager()->getReference(User:class, 1));
Please read the doctrine documentation it seems to me you are far from the good practices

Related

Doctrine Get the result of a DQL Query in a nested form

I have the following problem:
I have the following method that fetches the GPS points of a vessel:
/**
* #param array $mmsids
* #param unknown $longituteMin
* #param unknown $longtitudeMax
* #param unknown $latitudeMin
* #param unknown $latitudeMax
* #param \Datetime $timeInterval
*
* #throws EmptyParamGivenException
* #throws Exception
*
* #return Vesel[] with their routes
*/
public function getRoutes(array $mmsids=[],
$longituteMin=null,
$longtitudeMax=null,
$latitudeMin=null,
$latitudeMax=null,
\DateTime $fromDate=null,
\DateTime $toDate=null
) {
$em=$this->getEntityManager();
$query=$em->createQueryBuilder('v')
->from('AppBundle:Vesel', 'v')
->innerJoin('v.veselMoveStatuses','m')
->select('v.mmsi,m.logtitude,m.latitude,m.timestamp')
->addOrderBy('v.mmsi','ASC')
->addOrderBy('m.timestamp','DESC');
if(!empty($longituteMin)){
$query->andWhere('m.logtitude >= :long_min')->setParameter(':long_min',$longituteMin);
}
if(!empty($longtitudeMax)) {
$query->andWhere('m.logtitude <= :long_max')->setParameter(':long_max',$longituteMax);
}
if(!empty($latitudeMin)){
$query->andWhere('m.latitude >= :lat_min')->setParameter(':lat_min',$latitudeMin);
}
if(!empty($latitudeMax)){
$query->andWhere('m.latitude <= :lat_max')->setParameter(':lat_max',$latitudeMin);
}
if(!empty($mmsids)){
$query->andWhere('v.mmsi IN (:mmsids)')->setParameter('mmsids', $mmsids,\Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
}
$paramsToValidate=[RouteInputParameter::PARAM_DATE_FROM=>$fromDate,RouteInputParameter::PARAM_DATE_TO=>$toDate];
if($fromDate!==null && $toDate!==null){
InputValidator::dateRangeValidation($paramsToValidate,RouteInputParameter::PARAM_DATE_FROM,RouteInputParameter::PARAM_DATE_TO);
$query->andWhere('m.timestamp BETWEEN :date_min AND :date_max')
->setParameters(['date_min'=>$fromDate,'date_max'=>$toDate]);
} else if($fromDate!==null) {
$query->andWhere('m.timestamp <= :date_min')
->setParameters(['date_min'=>$fromDate]);
} else if($toDate!==null) {
$query->where('m.timestamp >= :date_max')
->setParameters(['date_max'=>$toDate]);
}
$query = $query->getQuery();
return $query->getResult();
}
What I want to achieve it that I want to generate the result in a nested way like that:
[
[
"mmsi"=>"^somevalue^"
points=>[
"longtitude":"^longtitude_value^",
"latitude":"^latitude_value^",
"time":"^time_value^"
],
....
],
....
]
do you have any idea if there is an internal Doctrine mechanism that allows me to do this or should I implement my own?
The Vessel Entity is:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="vessel",indexes={
* #ORM\Index(name="mmsi",columns={"mmsi"})
* })
*/
class Vesel
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #var integer
*/
private $id;
/**
* #ORM\Column(type="integer",name="mmsi")
* #var integer
*/
private $mmsi;
/**
* #ORM\OneToMany(targetEntity="VesselMoveStatus",mappedBy="vesel")
* #var \Doctrine\Common\Collections\Collection
*/
private $veselMoveStatuses;
/**
* Constructor
*/
public function __construct($mmsi)
{
$this->veselMoveStatuses = new \Doctrine\Common\Collections\ArrayCollection();
$this->setMmsi($mmsi);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set mmsi
*
* #param integer $mmsi
*
* #return Vesel
*/
public function setMmsi($mmsi)
{
$this->mmsi = $mmsi;
return $this;
}
/**
* Get mmsi
*
* #return integer
*/
public function getMmsi()
{
return $this->mmsi;
}
/**
* Add veselMoveStatus
*
* #param \AppBundle\Entity\VesselMoveStatus $veselMoveStatus
*
* #return Vesel
*/
public function addVeselMoveStatus(\AppBundle\Entity\VesselMoveStatus $veselMoveStatus)
{
$this->veselMoveStatuses[] = $veselMoveStatus;
return $this;
}
/**
* Remove veselMoveStatus
*
* #param \AppBundle\Entity\VesselMoveStatus $veselMoveStatus
*/
public function removeVeselMoveStatus(\AppBundle\Entity\VesselMoveStatus $veselMoveStatus)
{
$this->veselMoveStatuses->removeElement($veselMoveStatus);
}
/**
* Get veselMoveStatuses
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVeselMoveStatuses()
{
return $this->veselMoveStatuses;
}
}
And is related into VesselMoveStatus entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Vesel;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\VeselRouteRepository")
* #ORM\Table(name="vessel_position_status",indexes={
* #ORM\Index(name="position",columns={"long","lat"})
* })
*/
class VesselMoveStatus
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id=null;
/**
* #ORM\ManyToOne(targetEntity="Vesel",inversedBy="veselMoveStatuses")
* #ORM\JoinColumn(name="vesel_id", referencedColumnName="id")
* #var Vesel
*/
private $vesel=null;
/**
* #ORM\Column(name="status",type="integer")
* #var integer|null
*/
private $status=null;
/**
* #ORM\Column(name="speed",type="integer")
* #var integer|null
*/
private $speed=null;
/**
* #ORM\Column(name="long",type="float")
* #var float|null
*/
private $logtitude=null;
/**
* #ORM\Column(name="lat",type="float")
* #var float|null
*/
private $latitude=null;
/**
* #ORM\Column(name="course",type="integer")
* #var integer|null
*/
private $course=null;
/**
* #ORM\Column(name="heading",type="integer")
* #var integer|null
*/
private $heading=null;
/**
* #ORM\Column(name="rotation",type="integer")
* #var integer|null
*/
private $rotation=null;
/**
* #ORM\Column(name="timestamp",type="datetime")
* #var Datetime|null
*/
private $timestamp=null;
public function __construct(
Vesel $vesel=null,
$status=null,
$speed=null,
$long=null,
$lat=null,
$course=null,
$heading=null,
$rotation=null,
$timestamp=null
){
$this->setVesel($vesel)
->setStatus($status)
->setSpeed($speed)
->setLogtitude($long)
->setLatitude($lat)
->setCourse($course)
->setHeading($heading)
->setRotation($rotation)
->setTimestamp($timestamp);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set mmsi
*
* #param integer $mmsi
*
* #return VesselMoveStatus
*/
public function setMmsi($mmsi)
{
$this->mmsi = $mmsi;
return $this;
}
/**
* Get mmsi
*
* #return integer
*/
public function getMmsi()
{
return $this->mmsi;
}
/**
*
* #param integer $status
* #return \AppBundle\Entity\VesselMoveStatus
*/
public function setStatus($status)
{
$this->status=$status;
return $this;
}
/**
*
* #return \AppBundle\Entity\integer|NULL
*/
public function getStatus()
{
return $this->status;
}
/**
* Set speed
*
* #param integer $speed
*
* #return VesselMoveStatus
*/
public function setSpeed($speed)
{
$this->speed = $speed;
return $this;
}
/**
* Get speed
*
* #return float
*/
public function getSpeed()
{
return $this->speed/10;
}
/**
* Set logtitude
*
* #param integer $logtitude
*
* #return VesselMoveStatus
*/
public function setLogtitude($logtitude)
{
$this->logtitude = $this->sanitizeGpsCoordinate($logtitude);
return $this;
}
/**
* Get logtitude
*
* #return float
*/
public function getLogtitude()
{
return $this->logtitude;
}
/**
* Set latitude
*
* #param integer $latitude
*
* #return VesselMoveStatus
*/
public function setLatitude($latitude)
{
$this->latitude = $this->sanitizeGpsCoordinate($latitude);
return $this;
}
/**
* Get latitude
*
* #return float
*/
public function getLatitude()
{
$latitude=$this->latitude;
return $latitude;
}
/**
* Set course
*
* #param integer $course
*
* #return VesselMoveStatus
*/
public function setCourse($course)
{
$this->course = $course;
return $this;
}
/**
* Get course
*
* #return integer
*/
public function getCourse()
{
return $this->course;
}
/**
* Set heading
*
* #param integer $heading
*
* #return VesselMoveStatus
*/
public function setHeading($heading)
{
$this->heading = $heading;
return $this;
}
/**
* Get heading
*
* #return integer
*/
public function getHeading()
{
return $this->heading;
}
/**
* Set rotation
*
* #param integer $rotation
*
* #return VesselMoveStatus
*/
public function setRotation($rotation)
{
$this->rotation = $rotation;
return $this;
}
/**
* Get rotation
*
* #return integer
*/
public function getRotation()
{
return $this->rotation;
}
/**
* Set timesptamp
*
* #param string $timesptamp
*
* #return VesselMoveStatus
*/
public function setTimestamp($timesptamp)
{
$this->timestamp = date_create_from_format("Y-m-d H:i:s.u",$timesptamp);
return $this;
}
/**
* Get timesptamp
*
* #return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* Set vesel
*
* #param \AppBundle\Entity\Vesel $vesel
*
* #return VesselMoveStatus
*/
public function setVesel(\AppBundle\Entity\Vesel $vesel = null)
{
$this->vesel = $vesel;
return $this;
}
/**
* Get vesel
*
* #return \AppBundle\Entity\Vesel
*/
public function getVesel()
{
return $this->vesel;
}
/**
* Sometimes a GPS Coordinate may have the following format:
* 1,234532 if inserted as is then itn WONT be retreived correctly.
* Please use this method to sanitize the gps coordinate on setter method.
*
* #param string | float $coordinate
* #return number
*/
private function sanitizeGpsCoordinate($coordinate)
{
if(is_string($coordinate))
{
$coordinate=str_replace(',','.',$coordinate);
}
return (float)$coordinate;
}
}
The way you want to transform the data is not standard thus there is nothing generic in Doctrine to do so. But it's still very simple to achieve the objective you want.
However, IMHO the simplest solution is to use a closure to transform the result:
$result = $query->getResult();
$formatter = function($row) {
return [
"mmsi" => $row['mmsi']
"points" => [
"longtitude" => $row['logtitude'],
"latitude" => $row['latitude'],
"time" => $row['timestamp']
]
];
};
return array_map($formatter, $result);
The final array will have one element per point (veselMoveStatuses). If what you actually want is to have one element per vesel, consider changing the SELECT and adapt the formatter accordingly.
->select('v,m')
The result will be an array of Vesel objects with the veselMoveStatuses association already loaded (see this doc - section "Retrieve a CmsUser and fetch join all the phonenumbers he has").

Symfony Doctrine entity relations returns null data on saving

I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;

Doctrine form generation throws Twig error

I have a class that have relationships with other classes in my Bundle, and whenever I try to generate a form with the Doctrine command in Symfony, it fails by returning a Twig error
Key "school" for array with keys "id, startDate, endDate" does not exists in "form/formType.php.twig" at line 29
Here is my code:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Classroom
*
* #ORM\Table(name="classroom")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ClassroomRepository")
*/
class Classroom
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\School", inversedBy="classrooms")
* #ORM\JoinColumn(nullable=false)
*/
private $school;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Student", mappedBy="classroom")
* #ORM\JoinColumn(nullable=false)
*/
private $students;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Teacher")
* #ORM\JoinColumn(nullable=false)
*/
private $teachers;
/**
* #var \DateTime
*
* #ORM\Column(name="start_date", type="date")
*/
private $startDate;
/**
* #var \DateTime
*
* #ORM\Column(name="end_date", type="date")
*/
private $endDate;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set startDate
*
* #param \DateTime $startDate
*
* #return Classroom
*/
public function setStartDate($startDate)
{
$this->startDate = $startDate;
return $this;
}
/**
* Get startDate
*
* #return \DateTime
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* Set endDate
*
* #param \DateTime $endDate
*
* #return Classroom
*/
public function setEndDate($endDate)
{
$this->endDate = $endDate;
return $this;
}
/**
* Get endDate
*
* #return \DateTime
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* Set school
*
* #param \AppBundle\Entity\School $school
*
* #return Classroom
*/
public function setSchool(\AppBundle\Entity\School $school)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* #return \AppBundle\Entity\School
*/
public function getSchool()
{
return $this->school;
}
/**
* Constructor
*/
public function __construct()
{
$this->students = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add student
*
* #param \AppBundle\Entity\Student $student
*
* #return Classroom
*/
public function addStudent(\AppBundle\Entity\Student $student)
{
$this->students[] = $student;
return $this;
}
/**
* Remove student
*
* #param \AppBundle\Entity\Student $student
*/
public function removeStudent(\AppBundle\Entity\Student $student)
{
$this->students->removeElement($student);
}
/**
* Get students
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStudents()
{
return $this->students;
}
/**
* Add teacher
*
* #param \AppBundle\Entity\Teacher $teacher
*
* #return Classroom
*/
public function addTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers[] = $teacher;
return $this;
}
/**
* Remove teacher
*
* #param \AppBundle\Entity\Teacher $teacher
*/
public function removeTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers->removeElement($teacher);
}
/**
* Get teachers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTeachers()
{
return $this->teachers;
}
}
Do I need to add anything for it to works ? Is it because of the relationships with another class ?
Hope you can help me
As you didn't mention your Symfony version, it seems to me that you are having the same error as here:
Generating forms with Symfony 2.8 throws a Twig_Error_Runtime
Please check the solutions there
(Sorry for putting this in an answer, I don't have the reputation to comment in your question)

Why do my PrePersist and PreUpdate return null?

In my Doctrine Entity I'm trying to use the LifecycleCallbacks. For some reason the keep returning null
Timesheet Entity
namespace Petan\LogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Timesheet
*
* #ORM\Table(name="timesheet")
* #ORM\Entity(repositoryClass="Petan\LogBundle\Entity\TimesheetRepository")
* #ORM\HasLifecycleCallbacks
*/
class Timesheet
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="hours", type="decimal", precision=5, scale=1)
*/
private $hours;
/**
* #var \DateTime
*
* #ORM\Column(name="worked_at", type="date")
*/
private $workedAt;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
/**
* #var \DateTime
*
* #ORM\Column(name="started_at", type="time")
*/
private $startedAt;
/**
* #var \DateTime
*
* #ORM\Column(name="ended_at", type="time")
*/
private $endedAt;
/**
* #var boolean
*
* #ORM\Column(name="is_deleted", type="boolean")
*/
private $isDeleted;
/**
* toString
*
* #return string
*/
public function __toString()
{
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Timesheet
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Timesheet
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set hours
*
* #param string $hours
* #return Timesheet
*/
public function setHours($hours)
{
$this->hours = $hours;
return $this;
}
/**
* Get hours
*
* #return string
*/
public function getHours()
{
return $this->hours;
}
/**
* Set workedAt
*
* #param \DateTime $workedAt
* #return Timesheet
*/
public function setWorkedAt($workedAt)
{
$this->workedAt = $workedAt;
return $this;
}
/**
* Get workedAt
*
* #return \DateTime
*/
public function getWorkedAt()
{
return $this->workedAt;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return Work
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param \DateTime $updatedAt
* #return Work
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set startedAt
*
* #param \DateTime $startedAt
* #return Timesheet
*/
public function setStartedAt($startedAt)
{
$this->startedAt = $startedAt;
return $this;
}
/**
* Get startedAt
*
* #return \DateTime
*/
public function getStartedAt()
{
return $this->startedAt;
}
/**
* Set endedAt
*
* #param \DateTime $endedAt
* #return Timesheet
*/
public function setEndedAt($endedAt)
{
$this->endedAt = $endedAt;
return $this;
}
/**
* Get endedAt
*
* #return \DateTime
*/
public function getEndedAt()
{
return $this->endedAt;
}
/**
* Set isDeleted
*
* #param boolean $isDeleted
* #return Timesheet
*/
public function setIsDeleted($isDeleted)
{
$this->isDeleted = $isDeleted;
return $this;
}
/**
* Get isDeleted
*
* #return boolean
*/
public function getIsDeleted()
{
return $this->isDeleted;
}
/**
* #ORM\PrePersist
*/
public function prePersist() {
$this->created_at = new \DateTime;
$this->updated_at = new \DateTime;
// Set hours
$this->hours = $this->getDuration();
}
/**
* #ORM\PreUpdate
*/
public function preUpdate() {
$this->updated_at = new \DateTime;
// Set hours
$this->hours = $this->getDuration();
}
/**
* get Duration (in hours) between work's start-end time
* #param void
* #return float
*/
public function getDuration()
{
// Diff in seconds
$interval = $this->getEndedAt()->getTimestamp() - $this->getStartedAt()->getTimestamp();
// If value is negative, ended_at is the day after
// Add a day (in seconds)
if ($interval < 0)
$interval += (24*60*60);
// Returns hours
return $interval / (60*60);
}
}
The error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null
Note: i know there are similiar questions but they do not target this specific issue.
I think you are mixing property names using camel case and underscores.
You should always use camelCase as #kormik hint you
Stof Extensions could interest you : https://github.com/stof/StofDoctrineExtensionsBundle
/**
* #ORM\PrePersist
*/
public function prePersist() {
$this->createdAt = new \DateTime;
$this->updatedAt = new \DateTime;
//Better using setter : $this->setCreatedAt(new \DateTime());
// Set hours
$this->hours = $this->getDuration();
}
/**
* #ORM\PreUpdate
*/
public function preUpdate() {
$this->updatedAt = new \DateTime;
// Set hours
$this->hours = $this->getDuration();
}

error upon flushing an object with array of objects in association

i'm receiving the following error message upon persisting and flushing an object with its associations:
Catchable Fatal Error: Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 519 and defined in
.../vendor/doctrine/common/lib/Doctrine/Common/Collections/ArrayCollection.php line 48
what i have is a single table inheritance with this as the base object:
use Doctrine\ORM\Mapping as ORM;
/**
* ObjectData
*
* #ORM\Table(name="object_data")
* #ORM\Entity(repositoryClass="Edexp\CoreBundle\Entity\ObjectDataRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="entity_name", type="string")
* #ORM\DiscriminatorMap({
* "request" = "Edexp\MessageBundle\Entity\RequestData"
* })
* #ORM\HasLifecycleCallbacks
*/
class ObjectData
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var User
*
* #ORM\OneToMany(targetEntity="User", mappedBy="data")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="`key`", type="string", length=255)
*/
private $key;
/**
* #var string
*
* #ORM\Column(name="data", type="blob")
*/
private $data;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return ObjectData
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set user
*
* #param User $user
* #return ObjectData
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User
*/
public function getUser()
{
return $this->user;
}
/**
* Set key
*
* #param string $key
* #return ObjectData
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get key
*
* #return string
*/
public function getKey()
{
return $this->key;
}
/**
* Set data
*
* #param string $data
* #return ObjectData
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return string
*/
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prepareForPersist()
{
$this->created_at = new \DateTime();
}
}
and an additional object that inherits from ObjectData:
use Doctrine\ORM\Mapping as ORM;
use MyProject\CoreBundle\Entity\ObjectData;
/**
* RequestData
*
* #ORM\Entity()
*/
class RequestData extends ObjectData
{
/**
* var Request $request
*
* #ORM\ManyToOne(targetEntity="Request", inversedBy="data")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*/
private $request;
/**
* Set request
*
* #param Request $request
* #return RequestData
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get request
*
* #return Request
*/
public function getRequest()
{
return $this->request;
}
}
and here's the object that utilizes the RequestData entity:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Request
*
* #ORM\Table(name="requests")
* #ORM\Entity(repositoryClass="RequestRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Request
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Message $message
*
* #ORM\ManyToOne(targetEntity="Message", inversedBy="requests")
*/
private $message;
/**
* #var RequestType $type
*
* #ORM\ManyToOne(targetEntity="RequestType")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(
* targetEntity="RequestData",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $data;
/**
* #var datetime $created_at
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var text $comment
*
* #ORM\Column(name="comment", type="text")
*/
private $comment;
/**
* #var ArrayCollection $responses
*
* #ORM\OneToMany(
* targetEntity="Response",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $responses;
public function __construct()
{
$this->data = new ArrayCollection();
$this->responses = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set message
*
* #param Message $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* Get message
*
* #return Message
*/
public function getMessage()
{
return $this->message;
}
/**
* Set type
*
* #param RequestType $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return RequestType
*/
public function getType()
{
return $this->type;
}
/**
* Set created_at
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
}
/**
* Get created_at
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set comment
*
* #param text $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Get comment
*
* #return text
*/
public function getComment()
{
return $this->comment;
}
/**
* Add response
*
* #param Response $response
*/
public function addResponse($response)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $response->getUser() )
return;
}
$this->responses->add($response);
}
/**
* Get responses
*
* #return ArrayCollection
*/
public function getResponses()
{
return $this->responses;
}
public function hasResponse($user)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $user )
return $r;
}
return null;
}
public function addData($data)
{
$data->setRequest($this);
$this->data->add($data);
}
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$this->created_at = new \DateTime();
}
}
and finally the code that results in an error:
use MyProject\MessageBundle\Entity\Request as MyRequest;
$data = new RequestData();
$data->setUser($user);
$data->setKey('user_id');
$data->setData(6);
$req = new MyRequest();
$req->setMessage($message);
$req->setComment('bla');
$req->setType($doctrine->getRepository('MessageBundle:RequestType')->find(1));
$req->addData($data);
$em->persist($req);
$em->flush();
any suggestions as to what might be wrong here?
cheers
so here's what i had to do in order to make it work.
i had to change the association in ObjectData from:
#ORM\OneToMany(targetEntity="User", mappedBy="data")
to
#ORM\ManyToOne(targetEntity="User", inversedBy="data")
added the data field to the User entity accordingly.
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(targetEntity="ObjectData", mappedBy="user")
*/
private $data;
and voila, it worked.
Try:
$req->addData(array($data));
Explanation:
arrayCollection constructor type hints an array as its parameter, so you need to always pass it an array.

Categories