yii\base\Model::scenarios PHP Method

scenarios() public method

An active attribute is one that is subject to validation in the current scenario. The returned array should be in the following format: php [ 'scenario1' => ['attribute11', 'attribute12', ...], 'scenario2' => ['attribute21', 'attribute22', ...], ... ] By default, an active attribute is considered safe and can be massively assigned. If an attribute should NOT be massively assigned (thus considered unsafe), please prefix the attribute with an exclamation character (e.g. '!rank'). The default implementation of this method will return all scenarios found in the Model::rules declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes found in the Model::rules. Each scenario will be associated with the attributes that are being validated by the validation rules that apply to the scenario.
public scenarios ( ) : array
return array a list of scenarios and the corresponding active attributes.
    public function scenarios()
    {
        $scenarios = [self::SCENARIO_DEFAULT => []];
        foreach ($this->getValidators() as $validator) {
            foreach ($validator->on as $scenario) {
                $scenarios[$scenario] = [];
            }
            foreach ($validator->except as $scenario) {
                $scenarios[$scenario] = [];
            }
        }
        $names = array_keys($scenarios);
        foreach ($this->getValidators() as $validator) {
            if (empty($validator->on) && empty($validator->except)) {
                foreach ($names as $name) {
                    foreach ($validator->attributes as $attribute) {
                        $scenarios[$name][$attribute] = true;
                    }
                }
            } elseif (empty($validator->on)) {
                foreach ($names as $name) {
                    if (!in_array($name, $validator->except, true)) {
                        foreach ($validator->attributes as $attribute) {
                            $scenarios[$name][$attribute] = true;
                        }
                    }
                }
            } else {
                foreach ($validator->on as $name) {
                    foreach ($validator->attributes as $attribute) {
                        $scenarios[$name][$attribute] = true;
                    }
                }
            }
        }
        foreach ($scenarios as $scenario => $attributes) {
            if (!empty($attributes)) {
                $scenarios[$scenario] = array_keys($attributes);
            }
        }
        return $scenarios;
    }

Usage Example

Example #1
0
 public function scenarios()
 {
     $scenarios = parent::scenarios();
     $scenarios['login'] = ['username', 'password', 'verifyCode'];
     $scenarios['reg'] = ['username', 'password', 'verifyCode', 'confirmPassword'];
     return $scenarios;
 }
All Usage Examples Of yii\base\Model::scenarios