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

Weird situation with Models and events

Hi,

I was following the example described here:

https://docs.phalcon.io/en/latest/reference/models.html#implementing-events-in-the-model-s-class

Here is my model definition, the properties match the table columns.

<?php

namespace Models;

class Project extends \Phalcon\Mvc\Model {

public $id;
public $title;
public $description;
public $created;

public function beforeCreate()
{
    console.log('asdasd');die;
    $this->created = date('Y-m-d H:i:s');
}

public function getSource()
{
    return 'project';
}

}

Here is my model call from a controller:

$project = new \Models\Project(); $project->title = $title; $project->description = $description; //$project->created = date('Y-m-d H:i:s'); $project->save();

var_dump($project->getMessages());die;

I'm trying to populate the field created before insert the row to the table.

Here is the info I'm getting from the var_dump.

"array(1) { [0]=> object(Phalcon\Mvc\Model\Message)#51 (4) { ["_type":protected]=> string(10) "PresenceOf" ["_message":protected]=> string(19) "created is required" ["_field":protected]=> string(7) "created" ["_model":protected]=> NULL } } "

You can notice, I'm finishing php code in the beforeCreate event, an the php flow i ending in the var_dump, getting the message, the beforeCrate event is not getting call at all. I'm doing something wrong?



32.5k

Required fields are checked on validation but not on beforeCreate, which executes after validation. That's the reason. Use beforeValidationOnCreate to set required fields for 'create' queries.



12.1k

mmmm, very interesting, thanks.