Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifecycle Callback Issue When Extending FOSUserBundle User Entity

I've just imported the FOSUserBundle for the first time into a symfony2 project and I've noticed an issue when extending the user entity. I added created_at and updated_at fields with prePersist and preUpdate lifecycle callbacks but these methods are not being read.

If I put setters for these fields in the constructor then the fields are populated (but obviously this does not work correctly with updated_at). The other fields I have added have worked as expected.

Do you need to extend the UserListener in some way to allow the lifecycle events to work correctly?

Please find my code below, any help or advice would be greatly appreciated.

UserEntity:

namespace Acme\UserExtensionBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Acme\UserExtensionBundle\Entity\User
 *
 * @ORM\Table(name="acme_user")
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 */
class User extends BaseUser{

  /**
   * @var integer $id
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  protected $id;

  /**
   * @var datetime $created_at
   * @ORM\Column(name="created_at", type="datetime")
   */
  protected $created_at;

  /**
   * @var datetime $updated_at
   * @ORM\Column(name="updated_at", type="datetime")
   */
  protected $updated_at;

  ...

  public function __construct() {
    parent::__construct();
    $this->created_at = new \DateTime;
    $this->updated_at = new \DateTime;
  }

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

  ...
like image 484
Mark Avatar asked Aug 05 '26 19:08

Mark


1 Answers

After a quick look I can only spot a little error with the case of the Annotations name.

It should be

@ORM\PreUpdate

instead of

@ORM\preUpdate

which IMHO should lead to an error when executed.

Anyway I would suggest you to use the DoctrineExtensionsBundle described in http://symfony.com/doc/current/cookbook/doctrine/common_extensions.html .

It comes with a Timestampable (and many more useful) behaviours so you do not need to code this on your own (reinventing the wheel).

I'm using it together with FOSUserBundle and it works fine. This is how my definition in the User Entity looks like:

 /**
 * @var \DateTime $created
 *
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(type="datetime")
 */
protected $created;

/**
 * @var \DateTime  $updated
 *
 * @Gedmo\Timestampable(on="update")
 * @ORM\Column(type="datetime")
 */
protected $updated;
like image 124
room13 Avatar answered Aug 08 '26 12:08

room13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!