Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Models - using beforeCreate() does not appear to work

In my model I have:

    public function beforeCreate()
    {
        $this->created = date("Y:m:d H:i:s");
        $this->modified = date("Y:m:d H:i:s");
    }

    public function beforeUpdate()
    {
        $this->modified = date("Y:m:d H:i:s");
    }

In the database both columns are not null.

In the controller the record is either created or updated using save().

For existing records beforeUpdate() works and updates an existing date.

When creating a new record I get the following error messages on executing beforeCreate():

created is required
modified is required

Does this mean that I must always 'initialize' flelds created and modified before the record is created in the database?

I think so.

http://docs.phalconphp.com/en/latest/reference/models.html#events-and-events-manager



44.8k
Accepted
answer

Try beforeValidationOnCreate.



22.8k

I got confused as in traits and behaviours it infers I can use create in this way. But I guess this is only when you have a database column without NotNull attached.

<?php

trait MyTimestampable
{

    public function beforeCreate()
    {
        $this->created_at = date('r');
    }

    public function beforeUpdate()
    {
        $this->updated_at = date('r');
    }

}


22.8k

Right there. Thanks.

Try beforeValidationOnCreate.