如何将一个模型用于两种不同的形式? [英] how to use one model for two different forms?

查看:18
本文介绍了如何将一个模型用于两种不同的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在yii工作,我设计了一个用户模块,它包括用户注册用户登录 &修改密码规则.对于这三个过程,我只设计了一个 model,即 user model.在这个模型中,我定义了一个规则:

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'), 

此规则对 actionRegister 有效.但现在我想为 actionChangePassword,

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 ?

推荐答案

规则可以与场景相关联.只有当模型的当前 scenario 属性表明应该使用某个规则时,才会使用它.

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

示例模型代码:

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

这篇关于如何将一个模型用于两种不同的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆