【问题标题】:how to use one model for two different forms?如何将一个模型用于两种不同的形式?
【发布时间】:2013-01-05 07:48:16
【问题描述】:

我目前在yii工作,我设计了一个由user registraionuser loginchange password rule组成的用户模块。 对于这三个过程,我只设计了一个model,即user model。在这个模型中,我定义了一个规则:

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

此规则对actionRegister 有效。但现在我想为actionChangePassword 定义一个新的required rule

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

如何定义此操作的规则?

【问题讨论】:

    标签: yii yii-components


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多