symfony - How to insert datetime into `created` column only when a record is created first time -


  • i need solution insert datetime created column only when record created first time.

i've found example works onupdate style updates updated column every time when record updated.

/**  * @var datetime $updated  *   * @orm\column(type="datetime")  */ protected $updated;  /**  * @orm\prepersist  */ public function setupdatedprepersist() {     $this->updated = date('y-m-d h:i:s'); } 

an easy , reliable solution require following extension in composer: https://github.com/stof/stofdoctrineextensionsbundle/blob/master/resources/doc/index.rst

and update entity adding this:

<?php // src/yourcompany/yourbundle/entity/demo.php  namespace yourcompany\yourbundle\entity;  use gedmo\mapping\annotation gedmo; use doctrine\orm\mapping orm;  /**  * @orm\entity  */ class demo {     // ....     /**      * @var datetime $created      *      * @gedmo\timestampable(on="create")      * @orm\column(type="datetime")      */     private $created;      /**      * @var datetime $updated      *      * @gedmo\timestampable(on="update")      * @orm\column(type="datetime")      */     private $updated;  } 

that's it! :)

note: make sure enable timestampable listener in configuration, ie:

stof_doctrine_extensions:     orm:         default:             timestampable: true 

if don't standing on shoulders of giants:

<?php // src/yourcompany/yourbundle/entity/demo.php  namespace yourcompany\yourbundle\entity;  use doctrine\orm\mapping orm;  /**  * @orm\entity  * @orm\haslifecyclecallbacks  */ class demo {      // ...      /**      * @var datetime $created      *       * @orm\column(type="datetime")      */     protected $created;      /**      * @var datetime $updated      *       * @orm\column(type="datetime")      */     protected $updated;       /**      * @orm\prepersist      */     public function onprepersist()     {         $this->created = new \datetime();         $this->updated = new \datetime();     }      /**      * @orm\preupdate      */     public function onpreupdate()     {         $this->updated = new \datetime();     }      // ...  } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -