In my Symofny project I want for my entity to have timestamp field.
/**
* #ORM\Column(type="datetime", nullable=false)
*/
private $timestamp;
/**
* #ORM\PreUpdate
* #throws \Exception
*/
public function setTimestamp()
{
$this->timestamp = new DateTime("now");
return $this;
}
I want to be saved in timestamp format? How can I accomplish that?
Like // => 1387909800
I am on Symfony 4.3 version.
Try getTimestamp();
/**
* #ORM\Column(type="datetime", nullable=false)
*/
private $timestamp;
/**
* #ORM\PreUpdate
* #throws \Exception
*/
public function setTimestamp()
{
$date = new \DateTime();
$this->timestamp = $date->getTimestamp();
return $this;
}
Related
I'm creating an admin with easy admin bundle, i'm really new to Symfony4.
I've a button "create a category" and when i click on it, I've this error :
Return value of App\Entity\Category::getCreatedAt() must implement interface DateTimeInterface, null returned
Code:
<?php
namespace App\Entity;
use DateInterval;
use DateTimeZone;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
*/
class Category
{
use TimestampableTrait;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=8)
*/
private $ref;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="categoryId")
*/
private $products;
/**
* Category constructor.
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* #return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* #return string|null
*/
public function getRef(): ?string
{
return $this->ref;
}
/**
* #param string $ref
* #return $this
*/
public function setRef(string $ref): self
{
$this->ref = $ref;
return $this;
}
/**
* #return Collection|Product[]
*/
public function getProducts(): Collection
{
return $this->products;
}
/**
* #param Product $product
* #return $this
*/
public function addProduct(Product $product): self
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
$product->setCategoryId($this);
}
return $this;
}
/**
* #param Product $product
* #return $this
*/
public function removeProduct(Product $product): self
{
if ($this->products->contains($product)) {
$this->products->removeElement($product);
// set the owning side to null (unless already changed)
if ($product->getCategoryId() === $this) {
$product->setCategoryId(null);
}
}
return $this;
}
/**
* (PHP 5 >=5.5.0)<br/>
* Returns the difference between two DateTime objects
* #link https://secure.php.net/manual/en/datetime.diff.php
* #param DateTimeInterface $datetime2 <p>The date to compare to.</p>
* #param bool $absolute <p>Should the interval be forced to be positive?</p>
* #return DateInterval
* The https://secure.php.net/manual/en/class.dateinterval.php DateInterval} object representing the
* difference between the two dates or <b>FALSE</b> on failure.
*
*/
public function diff($datetime2, $absolute = false)
{
// TODO: Implement diff() method.
}
/**
* (PHP 5 >=5.5.0)<br/>
* Returns date formatted according to given format
* #link https://secure.php.net/manual/en/datetime.format.php
* #param string $format <p>
* Format accepted by {#link https://secure.php.net/manual/en/function.date.php date()}.
* </p>
* #return string
* Returns the formatted date string on success or <b>FALSE</b> on failure.
*
*/
public function format($format)
{
// TODO: Implement format() method.
}
/**
* (PHP 5 >=5.5.0)<br/>
* Returns the timezone offset
* #return int
* Returns the timezone offset in seconds from UTC on success
* or <b>FALSE</b> on failure.
*
*/
public function getOffset()
{
// TODO: Implement getOffset() method.
}
/**
* (PHP 5 >=5.5.0)<br/>
* Gets the Unix timestamp
* #return int
* Returns the Unix timestamp representing the date.
*/
public function getTimestamp()
{
// TODO: Implement getTimestamp() method.
}
/**
* (PHP 5 >=5.5.0)<br/>
* Return time zone relative to given DateTime
* #link https://secure.php.net/manual/en/datetime.gettimezone.php
* #return DateTimeZone
* Returns a {#link https://secure.php.net/manual/en/class.datetimezone.php DateTimeZone} object on success
* or <b>FALSE</b> on failure.
*/
public function getTimezone()
{
// TODO: Implement getTimezone() method.
}
/**
* (PHP 5 >=5.5.0)<br/>
* The __wakeup handler
* #link https://secure.php.net/manual/en/datetime.wakeup.php
* #return void Initializes a DateTime object.
*/
public function __wakeup()
{
// TODO: Implement __wakeup() method.
}
}
My TimestampableTrait
<?php
namespace App\Entity;
/**
* You must add the following comment on all the entities:
* #ORM\HasLifecycleCallbacks()
*/
trait TimestampableTrait
{
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="createdBy")
* #ORM\JoinColumn(nullable=true)
*/
protected $createdBy;
/**
* #return User|null
*/
public function getCreatedBy(): ?User
{
return $this->createdBy;
}
/**
* #param User|null $createdBy
* #return $this
*/
public function setCreatedBy(?User $createdBy): self
{
$this->createdBy = $createdBy;
return $this;
}
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
protected $createdAt;
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=false)
*/
protected $updatedAt;
/**
* Set the created at value on create
* #ORM\PrePersist()
* #param \DateTimeInterface $createdAt
* #return self
*/
public function setCreatedAt(\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Set the updated at value on update
* #ORM\PrePersist()
* #ORM\PreUpdate()
* #param \DateTimeInterface $updatedAt
* #return self
*/
public function setUpdatedAt(\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get - Created At
*
* #return \DateTimeInterface
*/
public function getCreatedAt(): \DateTimeInterface
{
return $this->createdAt;
}
/**
* Get - Updated At
*
* #return \DateTimeInterface|null
*/
public function getUpdatedAt(): \DateTimeInterface
{
return $this->updatedAt;
}
}
I really don't get where is the problem.
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
OK, tried to debug this problem for a few days and now i give up.
I have the followig form builder
Builder
->add('passDate', 'hidden', array('data'=>null, 'empty_data'=> date('Y-m-d',strtotime('1950-10-10'))))
->add('TDVLFirstIssue', 'hidden', array('data'=>null, 'empty_data'=> date('Y-m-d',strtotime('1950-10-10'))))
->add('TDVLExpiryDate', 'hidden', array('data'=>null, 'empty_data'=> date('Y-m-d',strtotime('2017-10-10'))));
and this is my entity
/**
* #var \DateTime
*
* #ORM\Column(name="passDate", type="date")
* #Assert\NotBlank()
*/
private $passDate;
/**
* #var \DateTime
*
* #ORM\Column(name="tdvlIssue", type="date")
* #Assert\NotBlank()
*/
private $TDVLFirstIssue;
/**
* #var \DateTime
*
* #Assert\GreaterThan(value = "+1 day midnight", message="Your TDVL require at least 1 month validity.")
* #ORM\Column(name="tdvlExpiry", type="date")
* #Assert\NotBlank()
*/
private $TDVLExpiryDate;
public function setPassDate($passDate)
{
$this->passDate = $passDate;
return $this;
}
/**
* Get passDate
*
* #return \DateTime
*/
public function getPassDate()
{
return $this->passDate;
}
public function setTDVLFirstIssue($tDVLFirstIssue)
{
$this->TDVLFirstIssue = $tDVLFirstIssue;
return $this;
}
/**
* Get tDVLFirstIssue
*
* #return \DateTime
*/
public function getTDVLFirstIssue()
{
return $this->TDVLFirstIssue;
}
**
* Set tDVLExpiryDate
*
* #param \DateTime $tDVLExpiryDate
*
* #return User
*/
public function setTDVLExpiryDate($tDVLExpiryDate)
{
$this->TDVLExpiryDate = $tDVLExpiryDate;
return $this;
}
/**
* Get tDVLExpiryDate
*
* #return \DateTime
*/
public function getTDVLExpiryDate()
{
return $this->TDVLExpiryDate;
}
And here is my controller
$entity = new User();
$form = $this->createSystemUserForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->setTDVLFirstIssue(date('Y-m-d',strtotime('1950-10-10')));
$entity->setTDVLExpiryDate(date('Y-m-d',strtotime('2018-10-10')));
$entity->setPassDate(date('Y-m-d',strtotime('1950-10-10')));
}
What i am trying to do is i want to pass default date to the database. so i tried with vanilla php format converting function data and format . But when i submit the form, it throw me this error which is
Error: Call to a member function format() on string
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value->format($platform->getDateFormatString()) : null;
}
. I understood that $passDate, $TDVLFirstIssue and $TDVLExpiryDate cannot be blank , which defined in entity as NotBlank(). I suspect that it is because of unsuccessful string to date conversion. So can help me about this problem? thanks in advance.
Note: Please take note that i am using symfony 2.7.
I change my builder date as follow and it works.
builder
->add('passDate', 'hidden', array('data'=>null, 'empty_data'=> date_create('1950-10-10')))
->add('TDVLFirstIssue', 'hidden', array('data'=>null, 'empty_data'=> date_create('1950-10-10')))
->add('TDVLExpiryDate', 'hidden', array('data'=>null, 'empty_data'=> date_create('2017-10-10')));
Hope it helps.
i'm stuck in error when try to generate CRUD in symfony2 I always get the following exception:
"Unable to transform value for property path "xxx": Expected a \DateTime or \DateTimeInterface."
it always happened with the any datetime field here is excerpt of my entity field:
/**
* #var \DateTime
*
* #ORM\Column(name="date_added", type="datetime", nullable=false)
*/
private $dateAdded = '0000-00-00 00:00:00';
/**
* Set dateAdded
*
* #param \DateTime $dateAdded
*
* #return User
*/
public function setDateAdded()
{
$this->dateAdded = new \DateTime();
return $this;
}
/**
* Get dateAdded
*
* #return \DateTime
*/
public function getDateAdded()
{
return $this->dateAdded;
}
-Also i tried to use easyadmin bundle which generate backend from entities using symfony2 CRUD on the fly but also get the same error so is there something wrong with my entity ?
Maybe removing the annotation #param \DateTime $dateAdded as your function setDateAdded() has no parameter ?
The $dateAdded field cannot contain a string. It needs to have a DateTime object, because that's whats expected. In other words you need to have a constructor which sets the date:
/**
* #var \DateTime
*
* #ORM\Column(name="date_added", type="datetime", nullable=false)
*/
private $dateAdded;
public function __construct() {
$this->dateAdded = new \DateTime();
}
Also, you need to accept a parameter on your setDate method:
public function setDate($date) {
$this->dateAdded = $date;
}
As a side note, keep in mind you will need to use a date filter if you'll be displaying the date in a twig template:
{{ entity.dateAdded|date('d.m.Y') }}
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();
}