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

Optional Columns in Models

I know there are skip attributes like below. But is there an optionalAttribute() or anything? For example, if a user registers with Google+ instead of the default login form, he won't need his email so it should allow an optional value.

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


98.9k
Accepted
answer

You can mark the column as not null in the table and add a validation like this:

<?php

use Phalcon\Mvc\Model,
    Phalcon\Mvc\Model\Message;

class Users extends Model
{
    public function beforeValidationOnCreate()
    {
        if ($this->authType != "google+") {            
            $this->appendMessage(new Message(
                "Email is required",
                "authType"                
            ));
            return false;
        }
        return true;        
    }

}