Symfony2 ORM prePersist Not Working

2019-02-21 10:22发布

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

<?php

namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Users
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class Users
{
    /**
     * @var string
     *
     * @ORM\Column(name="username", type="string", length=255, nullable=false)
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="firstname", type="string", length=255, nullable=false)
     */
    private $firstname;

    /**
     * @var string
     *
     * @ORM\Column(name="lastname", type="string", length=255, nullable=false)
     */
    private $lastname;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=false)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=32, nullable=false)
     */
    private $password;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean", nullable=false)
     */
    private $active;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime", nullable=false)
     */
    private $created;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="modified", type="datetime", nullable=false)
     */
    private $modified;

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



    /**
     * Set username
     *
     * @param string $username
     * @return Users
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string 
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set firstname
     *
     * @param string $firstname
     * @return Users
     */
    public function setFirstname($firstname)
    {
        $this->firstname = $firstname;

        return $this;
    }

    /**
     * Get firstname
     *
     * @return string 
     */
    public function getFirstname()
    {
        return $this->firstname;
    }

    /**
     * Set lastname
     *
     * @param string $lastname
     * @return Users
     */
    public function setLastname($lastname)
    {
        $this->lastname = $lastname;

        return $this;
    }

    /**
     * Get lastname
     *
     * @return string 
     */
    public function getLastname()
    {
        return $this->lastname;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return Users
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string 
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return Users
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string 
     */
    public function getPassword()
    {
        return $this->password;
    }

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

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean 
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Users
     */
    public function setCreated()
    {
        $this->created = $created;

        return $this;        
    }

    /**
     * Get created
     *
     * @return \DateTime 
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set modified
     *
     * @param \DateTime $modified
     * @return Users
     */
    public function setModified()
    {
        $this->modified = $modified;

        return $this;
    }

    /**
     * Get modified
     *
     * @return \DateTime 
     */
    public function getModified()
    {
        return $this->modified;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
    * @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');

    }
}

Here is my code of Form/UsersType.php

<?php
namespace Acme\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;


class UsersType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username','text', array('required' => true))
            ->add('firstname','text', array('required' => true))
            ->add('lastname','text', array('required' => true))
            ->add('email', 'email', array('label' => 'E-Mail'))
            ->add('password', 'password', array('label' => 'Password'))
            ->add('password_confirmation', 'password', array('mapped' => false)) // Added virtual field on form
/*                
            ->add('active','hidden',array('data' => ''))
            ->add('created','hidden',array('data' => ''))
            ->add('modified','hidden',array('data' => ''))
 * 
 */
        ;        
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\Users'
        ));
    }

    public function getName()
    {
        return 'acme_demobundle_userstype';
    }
}

I have commented out these three fields active, created and modified to not display them in the form.

But i am getting error:

An exception occurred while executing 'INSERT INTO users (username, firstname, lastname, email, password, active, created, modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' with params ["neeraj", "neeraj", "kumar", "neeraj.kumar@test.com", "p@ssw0rd", null, null, null]:

What i am missing in the Entity?

Stack Trace

Stack Trace (Plain Text)  -

[1] Doctrine\DBAL\DBALException: An exception occurred while executing 'INSERT INTO users (username, firstname, lastname, email, password, active, created, modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' with params ["neeraj", "neeraj", "kumar", "neeraj.kumar@rsystems.com", "p@ssw0rd", null, null, null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'active' cannot be null
    at n/a
        in C:\wamp\www\Symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php line 47

    at Doctrine\DBAL\DBALException::driverExceptionDuringQuery(object(PDOException), 'INSERT INTO users (username, firstname, lastname, email, password, active, created, modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', array('neeraj', 'neeraj', 'kumar', 'neeraj.kumar@rsystems.com', 'p@ssw0rd', null, null, null))
        in C:\wamp\www\Symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 140

    at Doctrine\DBAL\Statement->execute()
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 277

    at Doctrine\ORM\Persisters\BasicEntityPersister->executeInserts()
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 929

    at Doctrine\ORM\UnitOfWork->executeInserts(object(ClassMetadata))
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 318

    at Doctrine\ORM\UnitOfWork->commit(null)
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php line 355

    at Doctrine\ORM\EntityManager->flush()
        in C:\wamp\www\Symfony\src\Acme\DemoBundle\Controller\UsersController.php line 55

    at Acme\DemoBundle\Controller\UsersController->createAction(object(Request))
        in  line 

    at call_user_func_array(array(object(UsersController), 'createAction'), array(object(Request)))
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2774

    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2748

    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2878

    at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2179

    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in C:\wamp\www\Symfony\web\app_dev.php line 28

[2] PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'active' cannot be null
    at n/a
        in C:\wamp\www\Symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 138

    at PDOStatement->execute(null)
        in C:\wamp\www\Symfony\vendor\doctrine\dbal\lib\Doctrine\DBAL\Statement.php line 138

    at Doctrine\DBAL\Statement->execute()
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php line 277

    at Doctrine\ORM\Persisters\BasicEntityPersister->executeInserts()
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 929

    at Doctrine\ORM\UnitOfWork->executeInserts(object(ClassMetadata))
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 318

    at Doctrine\ORM\UnitOfWork->commit(null)
        in C:\wamp\www\Symfony\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php line 355

    at Doctrine\ORM\EntityManager->flush()
        in C:\wamp\www\Symfony\src\Acme\DemoBundle\Controller\UsersController.php line 55

    at Acme\DemoBundle\Controller\UsersController->createAction(object(Request))
        in  line 

    at call_user_func_array(array(object(UsersController), 'createAction'), array(object(Request)))
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2774

    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2748

    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2878

    at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
        in C:\wamp\www\Symfony\app\bootstrap.php.cache line 2179

    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in C:\wamp\www\Symfony\web\app_dev.php line 28

4条回答
够拽才男人
2楼-- · 2019-02-21 11:12

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

查看更多
forever°为你锁心
3楼-- · 2019-02-21 11:22

I solved this issue cleaning the cache!

php bin/console cache:clear
查看更多
Ridiculous、
4楼-- · 2019-02-21 11:24

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
{
    // ...
}
查看更多
forever°为你锁心
5楼-- · 2019-02-21 11:24

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();

}
查看更多
登录 后发表回答