We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.

https://docs.phalcon.io/en/latest/reference/models.html#events-and-events-manager



47.7k

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');
    }

}


47.7k

Right there. Thanks.

Try beforeValidationOnCreate.