YII2之 Scenario

使用方法

// scenario is set as a property
$model = new User;
$model->scenario = User::SCENARIO_SHOW; // scenario is set through configuration
$model = new User(['scenario' => User::SCENARIO_SUBMIT]);

举例说明

<?php

namespace app\models;

use yii\base\Model;

class ContactForm extends Model
{
public $username;
public $password;
public $email; const SCENARIO_SHOW = 'show';
const SCENARIO_SUBMIT = 'submit'; public function scenarios()
{
return [
self::SCENARIO_SHOW => ['username', 'password'],
self::SCENARIO_SUBMIT => ['username', 'email', 'password'],
];
} public function rules()
{
return [
// username, email and password are all required in "submit" scenario
[['username', 'email', 'password'], 'required', 'on' => self::SCENARIO_SUBMIT], // username and password are required in "show" scenario
[['username', 'password'], 'required', 'on' => self::SCENARIO_SHOW],
];
} public function attributeLabels()
{ switch($this->scenario)
{
case self::SCENARIO_SHOW:
$labels = [
'username' => 'User Name',
'password' => 'Password',
];
break; case self::SCENARIO_SUBMIT:
$labels = [
'username' => 'User Name',
'password' => 'Password',
'email' => 'Your email address',
];
break;
}
return $labels;
}
}
上一篇:[Algorithm] Graph


下一篇:Ice-E(Embedded Internet Communications Engine)移植到s3c2440A(arm9)linux(2.6.12)上的