使用方法
// 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;
}
}