質問

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 ?

役に立ちましたか?

解決

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,
  ));
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top