how to use one model for two different forms?

醉酒当歌 提交于 2019-12-12 01:17:35

问题


I am currently working in yii, I have designed a user module which consists user registraion, user login & change password rule. for these three process I have designed only one model i.e. user model. in this model I have defined a rule:

array('email, password, bus_name, bus_type', 'required'), 

This rule is valid for actionRegister. but now I want to define a new required rule for actionChangePassword,

array('password, conf_password', 'required'), 

How can I define rule for this action ?


回答1:


Rules can be associated with scenarios. A certain rule will only be used if the model's current scenario property says it should.

Sample model code:

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), 
    );
  }

}

Sample controller code:

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,
  ));
}


来源:https://stackoverflow.com/questions/14169814/how-to-use-one-model-for-two-different-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!