Difference between #40 and #41 of
Yii for beginners 2

Revision #41 has been created by rackycz on Mar 17, 2022, 10:43:17 AM with the memo:

Each validator
« previous (#40) next (#42) »

Changes

Title unchanged

Yii for beginners 2

Category unchanged

Tutorials

Yii version unchanged

1.1

Tags unchanged

Yii,mvc,tutorial,beginner

Content changed

[...]
1st = resetScope()

2nd = defaultScope()

3rd = custom scope

 
 
17. Each validator (see Yii2)
 
------------------------------------
 
 
If you need the "each validator" (for validating array of values) which is available in Yii2, you paste this method to your model and use it as the validator. Do not forget to specify validation rules for the particular values as well! See examples below.
 
 
```php
 
public function each($attribute, $params)
 
{
 
  $attr = $this->$attribute;
 
  if (!is_array($attr)) {
 
    $attr = [$attr];
 
  }
 
 
  $validatorName = $params['rule'][0];
 
  $validatorParams = array_slice($params['rule'], 1);
 
  $validatedAttributes = [$attribute];
 
  $model = new self(); // Better would be to create a brand new model dynamically
 
  $validator = CValidator::createValidator($validatorName, $model, $validatedAttributes, $validatorParams);
 
 
  foreach ($attr as $value) {
 
    $model->$attribute = $value;
 
    $validator->validate($model, $validatedAttributes);
 
    foreach ($model->getErrors($attribute) as $e) {
 
      $this->addError($attribute, $e);
 
    }
 
    $model->clearErrors();
 
  }
 
}
 
```
 
 
Usage is standard:
 
 
```php
 
public function rules()
 
{
 
  return array(
 
    array('myColumn', 'each', 'rule' => ['validatorName', 'optionalParamA' => 1]),
 
  );
 
}
 
```
 
 
Where "validatorName" can be either an existing validator class or your custom validation method within your model. No difference here.
 
 
```php
 
public function validatorName($attribute, $params)
 
{
 
  $val = $this->$attribute;
 
  $paramA = $params['optionalParamA']??'Not set';
 
  $this->addError($attribute, 'An error text');
 
}
 
```
15 0
21 followers
Viewed: 85 520 times
Version: 1.1
Category: Tutorials
Written by: rackycz
Last updated by: rackycz
Created on: Mar 5, 2013
Last updated: 2 years ago
Update Article

Revisions

View all history