Hello i have problem with Sonata bundle when i want to create new post i get message
[2/3] DBALException: An exception occurred while executing 'INSERT INTO post (title, status, body, created, updated) VALUES (?, ?, ?, ?, ?)' with params ["Hello World", 1, "asdasda", null, "2014-04-29 18:05:10"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created' cannot be null
In my entity class i use @ORM\HasLifecycleCallbacks() for created and updated actions.
Entity
use Doctrine\ORM\Mapping as ORM;
/**
* Post
*
* @ORM\HasLifecycleCallbacks()
* @ORM\Table(name="post")
* @ORM\Entity(repositoryClass="ISLab\Bundles\BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var integer
*
* @ORM\Column(name="status", type="integer")
*/
private $status;
/**
* @var string
*
* @ORM\Column(name="body", type="text", nullable=true)
*/
private $body;
/**
* @var datetime
*
* @ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* @var datetime
*
* @ORM\Column(name="updated", type="datetime")
*/
private $updated;
This is method what i use in entity for create and update.
/*
* Set Date Created
*
* @ORM\PrePersist
*
* @return \DateTime
*/
public function setCreated()
{
return $this->created = new \DateTime(date('Y-m-d H:i:s'));
}
/**
* Get Date Created
*
* @return Post
*/
public function getCreated()
{
return $this->created;
}
/**
* Set Date Modified
*
* @ORM\PrePersist
* @ORM\PreUpdate
*
* @return Post
*/
public function setUpdated()
{
$this->updated = new \DateTime();
return $this;
}
/**
* Get Udated Date
*
* @return Post
*/
public function getUpdated()
{
return $this->updated;
}
Update action work fine and he is allways automaticly called when i edit any post. But when i try to create new post created value is null idk whay?
According to the error message, the created attribute is null when you insert the new entity. You have to set a value for this attribute.
You can set it in the Entity class constructor:
class Post
{
public function __construct()
{
$this->created = new \DateTime();
}
...
Or you can set it before persisting your entity by calling setCreated().
/**
* @ORM\PrePersist()
*/
public function prePersist()
{
if ($this->created == null) $this->created = new \DateTime();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With