0

I am on Symfony 4, and I have a problem with Lifecycle callbacks. I have two classes, one model and a child of this model. I would like that every child of the model have the same PrePersist callback but the callback is not triggered. Is it normal or did I do something wrong ?

<?php
// src/Models/QuestionModel.php

namespace App\Models;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ODM\MappedSuperclass
 * @ODM\HasLifecycleCallbacks
 */
class QuestionModel
{
  /**
   * @ODM\Id(strategy="AUTO")
   */
  protected $id;

  /**
   * @ODM\Field(type="date")
   */
  protected $createdAt;

  /**
   * @ODM\PrePersist
   */
  public function setCreatedAtValue() {
    $this->createdAt = new \DateTime();
  }

and the child:

<?php
// src/Document/CDN/Question.php

namespace App\Document\CDN;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use App\Models\QuestionModel;

/**
 * @ODM\Document(collection="CDNQuestion")
 * @ODM\HasLifecycleCallbacks
 */
class Question extends QuestionModel
{
}

If it is normal that it does not work, do you have a solution for my problem ?

Thx

Arcades
  • 150
  • 1
  • 13

1 Answers1

0

I would recommend to create separate class for that. Trait should be excellent choice. I have something like that in my projects.

trait TimestampableTrait
{
    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=false)
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $updatedAt;

    /**
     * @ORM\PrePersist
     */
    public function updateCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

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

    /**
     * @return \DateTime|null
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @return string
     */
    public function getCreatedAtFormatted()
    {
        if ($this->createdAt instanceof \DateTime) {
            return $this->createdAt->format('d/m/Y h:i:s A');
        }

        return '';
    }
}