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

skipAttributesOnUpdate seems not to work in Models

I have a model "User" that I want to validate the email-address of a user on create, but not on update.

<?php
use \Phalcon\Mvc\Model\Validator\Email,
    \Phalcon\Mvc\Model\Validator\Uniqueness;

class User extends \Phalcon\Mvc\Model {
    public $id;
    public $email;

    public function validation()
    {
        $this->validate(new Email(array(
            "field"    => "email",
            "required" => true,
        )));

        $this->validate(new Uniqueness(array(
        "field"    => "email",
        'message' => _('A user already exists for this email address')
        )));
    }

    public function initialize()
    {
        $this->skipAttributesOnUpdate(array('email'));
        parent::initialize();
    }

}

I have tried replacing $this->skipAttributesOnUpdate() with $this->skipAttributes(), with no luck.

I ended up with adding if(!isset($this->id)) in the validation method, is this correct? Phalcon v. 2.0.3



34.6k
Accepted
answer

skipAttributesOnUpdate just ignores the specified fields in the update operation, however the attribute is still part of the model and there is a validation (Uniqueness) to be applied on that model.

edited Jul '20

What I did and worked is

in model

public function setAttributesOnUpdate($data = []) { $this->skipAttributesOnUpdate($data); }

in controller

$usersModel->setAttributesOnUpdate([ 'fullname', 'user', 'password' ]);

Use this before save() or update()