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

`notNullValidations => false` not working??

It seems that notNullValidations => false is not working on model->save().

Detail is below.

class ModelBase extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        \Phalcon\Mvc\Model::setup([
            'notNullValidations' => false
        ]);
    }
}
use Phalcon\Validation\Validator\Email as EmailValidator;

class User extends ModelBase
{
     public function handleSaveError()
     {
         $this->handleError('save');
     }

     public function handleError($type = 'save')
     {
        if ($this->getMessages()) {
            $messages = '';
            foreach ($this->getMessages() as $message) {
                $msg = sprintf('(field: %s, message: %s)', $message->getField(), $message->getMessage());
                $messages .= '    ' . $msg . "\n";
            }
            throw new \Exception("Model $type error:" . "\n" . $messages);
        }
     }

     public function validation()
    {
        $validator = new Validation();

        $validator->rules('email', [
            new EmailValidator(array(
            )),
        ]);

        return $this->validate($validator);
    }
}
$user = User::findFirstById($userId);
$user->setEmail(null);
$user->save() or $user->handleSaveError();

then I got

2016-08-30 18:57:04 [ERROR] Model save error:
    (field: email, message: Field email must be an email address)

How do I solve this??

Anyone help!

Try

$validator->rules('email', [
    new EmailValidator(array[
        'message' => 'The e-mail is not valid',
        'allowEmpty' => true
    ]),
]);


2.2k
edited Aug '16

Thank you. But why below dosn't work?

 \Phalcon\Mvc\Model::setup([
    'notNullValidations' => false 
  ]);

'allowEmpty' => true is only way to skip null validation??

Check out https://docs.phalcon.io/pl/latest/reference/models.html#disabling-enabling-features

notNullValidations => false disables not null columns check with your database.

If you want to tell the EmailValidator to accept empty values use the the code I posted above.



2.2k

OK, I got it! Thank you for your teaching.

notNullValidations is whole other thing, it's for preventing inserting null values into database, If you want validator to accept empty values you need to use allowEmpty