yii\validators\ExistValidator::validateAttribute PHP Method

validateAttribute() public method

public validateAttribute ( $model, $attribute )
    public function validateAttribute($model, $attribute)
    {
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
        if (is_array($targetAttribute)) {
            if ($this->allowArray) {
                throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
            }
            $params = [];
            foreach ($targetAttribute as $k => $v) {
                $params[$v] = is_int($k) ? $model->{$v} : $model->{$k};
            }
        } else {
            $params = [$targetAttribute => $model->{$attribute}];
        }
        if (!$this->allowArray) {
            foreach ($params as $value) {
                if (is_array($value)) {
                    $this->addError($model, $attribute, Yii::t('yii', '{attribute} is invalid.'));
                    return;
                }
            }
        }
        $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
        $query = $this->createQuery($targetClass, $params);
        if (is_array($model->{$attribute})) {
            if ($query->count("DISTINCT [[{$targetAttribute}]]") != count($model->{$attribute})) {
                $this->addError($model, $attribute, $this->message);
            }
        } elseif (!$query->exists()) {
            $this->addError($model, $attribute, $this->message);
        }
    }

Usage Example

 /**
  * Validates the attribute using the "exist" validator
  * @param \yii\base\Model $model the data model to be validated
  * @param string $attribute the name of the attribute to be validated.
  */
 private function validateExist($model, $attribute)
 {
     if ($this->targetClass === null) {
         throw new InvalidConfigException('The "targetClass" property must be set.');
     }
     if (!is_string($this->targetAttribute)) {
         throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.');
     }
     $validator = new ExistValidator();
     $validator->targetClass = $this->targetClass;
     $validator->targetAttribute = $this->targetAttribute;
     $validator->validateAttribute($model, $attribute);
 }
All Usage Examples Of yii\validators\ExistValidator::validateAttribute