我目前正在yii
工作,我设计了一个用户模块,其中包含user registraion
,user login
& change password rule
。
对于这三个过程,我只设计了一个model
,即user model
。在这个模型中我定义了一个规则:
array('email, password, bus_name, bus_type', 'required'),
此规则适用于actionRegister
。但现在我想为required rule
定义一个新的actionChangePassword
,
array('password, conf_password', 'required'),
如何为此操作定义规则?
答案 0 :(得分:3)
Rules can be associated with scenarios。只有当模型的当前scenario
属性表明它应该使用时,才会使用某个规则。
示例型号代码:
class User extends CActiveRecord {
const SCENARIO_CHANGE_PASSWORD = 'change-password';
public function rules() {
return array(
array('password, conf_password', 'required', 'on' => self::SCENARIO_CHANGE_PASSWORD),
);
}
}
示例控制器代码:
public function actionChangePassword() {
$model = $this->loadModel(); // load the current user model somehow
$model->scenario = User::SCENARIO_CHANGE_PASSWORD; // set matching scenario
if(Yii::app()->request->isPostRequest && isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if($model->save()) {
// success message, redirect and terminate request
}
// otherwise, fallthrough to displaying the form with errors intact
}
$this->render('change-password', array(
'model' => $model,
));
}