问题
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();
}
...
回答1:
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;
来源:https://stackoverflow.com/questions/9806184/lifecycle-callback-issue-when-extending-fosuserbundle-user-entity