简体   繁体   中英

Phalcon PHP: determine if create or update in model validation method

I've created a Model in Phalcon. In it, I have a validation() method. On create of a record, I want to make sure that a record is getting a name, but I don't want that to be required on update. How can I determine that with Phalcon?

It is described better in the Phalcon's docs .



class Robots extends \Phalcon\Mvc\Model
{

    public function initialize()
    {
        //Skips fields/columns on both INSERT/UPDATE operations
        $this->skipAttributes(array('year', 'price'));

        //Skips only when inserting
        $this->skipAttributesOnCreate(array('created_at'));

        //Skips only when updating
        $this->skipAttributesOnUpdate(array('modified_in'));
    }

}

If you have something more complex and want to use the same 'validation' method for both creates and updates you can do this:

public function beforeValidationOnCreate()
{
    $this->_isCreate = 1;
}

public function beforeValidationOnUpdate()
{
    $this->_isCreate = 0;
}

public function validation()
{
    if ($this->_isCreate) {
        // ...
    } else {
        // ...
    }
}

You can do your validations within a function called beforeValidationOnCreate or beforeCreate and it gets hit only on Creation and not updating

public function beforeValidationOnCreate()
{
    //Do the validations
}

or

class MyModel extends \Phalcon\Mvc\Model
{
    public function beforeCreate()
    {
        //Do the validations
    }
}

Check the link below for more Events that you could use :

Phalcon PHP Events and Events Manager

Hope that is close to what you need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM