How to implement uniquevalidator.

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

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

......
}


824

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



824

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. http://stackoverflow.com/questions/13873094/phalcon-odm-validation-messages