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

How to implement uniquevalidator.

How to implement uniquevalidator for ODM model validation (Phalcon >= 2.0)



5.2k
edited May '15
use Phalcon\Mvc\Model\Validator\Uniqueness as Uniqueness;

class Post extends \Model\BaseModel
{

public function validation()
{
      $this->validate(new Uniqueness(array(
          'field' => 'slug',
          'message' => 'The slug already exists in other articles,please modify the article title'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
}

......
}


1.4k

Thx for your reply but this code is not working for ODM + Mongo DB



1.4k

I Have this code but it not working in phalcon version >= 2.0

<?php

use Phalcon\Mvc\Model\Validator,
Phalcon\Mvc\Model\ValidatorInterface;

class UniqueValidator extends Validator implements ValidatorInterface
{

    public function validate($record)
    {
        $field = $this->getOption('field');
        if ($record->count(array("field" => $record->readAttribute($field)))) {
            $this->appendMessage("The ".$field." must be unique", $fieldName, "Unique");
            return false;
        }
        return true;
    }
}

Code ref. https://stackoverflow.com/questions/13873094/phalcon-odm-validation-messages