how to use one model for two different forms?

2019-08-17 16:05发布

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条回答
Melony?
2楼-- · 2019-08-17 16:06

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,
  ));
}
查看更多
登录 后发表回答