Symfony2 ORM prePersist Not Working

后端 未结 5 1159
既然无缘
既然无缘 2021-01-08 00:15

prePersist() method of my entity is not being invoked.



        
相关标签:
5条回答
  • 2021-01-08 00:50

    I have the same problem. According to docs you must enable lifecycle callbacks http://symfony.com/doc/current/book/doctrine.html

    /**
     * @ORM\Entity()
     * @ORM\HasLifecycleCallbacks()
     */
    class Product
    {
        // ...
    }
    
    0 讨论(0)
  • 2021-01-08 00:54

    I had the same issue, it was because my method was private, so make sure the method with @ORM\PrePersist() annotation is public.

    0 讨论(0)
  • 2021-01-08 00:56

    @ORM\PrePersist is missing parenthesis, it should be @ORM\PrePersist()

    0 讨论(0)
  • 2021-01-08 01:01

    One issue is this function.

    /**
     * Set active
     *
     * @ORM\PrePersist
     * @param boolean $active
     * @return Users
     */
    public function setActive($active)
    {
        $this->active = $active;
    
        return $this;
    }
    

    You can't pass arguments to functions when using @PrePersist.

    Also this function

    /**
    * @ORM\PrePersist
    * @ORM\PreUpdate
    */
    public function prePersist(){
    
      $this->active = 0;
      $this->created = date('Y-m-d H:i:s');
      $this->modified = date('Y-m-d H:i:s');
    
    }
    

    fails because you are assigning a string value to DateTime fields. Try this:

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function prePersist()
    {
    
      $this->active = false;
      $this->created = new \DateTime();
      $this->modified = new \DateTime();
    
    }
    
    0 讨论(0)
  • 2021-01-08 01:07

    I solved this issue cleaning the cache!

    php bin/console cache:clear
    
    0 讨论(0)
提交回复
热议问题