Doctrine2 override save method

With Doctrine2 you cannot override save method but you can execute preUpdate() method.
See below how to implement it.

On your entity class, for example AdminBundle/Entity/Annonce.php, add the HasLifecycleCallbacks annontation

/**
 * @ORM\Entity(repositoryClass="Tripix\AdminBundle\Repository\AnnonceRepository")
 * @ORM\HasLifecycleCallbacks
 */

And your method, with the annotation

/** @ORM\PreUpdate() */
        public function preUpdate()
        {
                $this->created_at = new \DateTime("now");
        }

That’s all, it should works.

A complete example, just in case :

<?php
namespace Tripix\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * @ORM\Entity(repositoryClass="Tripix\AdminBundle\Repository\AnnonceRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Annonce
{

/** @ORM\PreUpdate() */
        public function preUpdate()
        {
                $this->created_at = new \DateTime("now");
        }

    public function __construct()
    {
        $this->created_at = new \DateTime("now");
        $this->visuels = new ArrayCollection();
    }

Leave a Reply