How to reuse Yii form using scenario

1.8k Views Asked by At

I have Registration model(which has fields login, password, email, mobile) and want to use some of the fields from Registration(like login and password) in a login action, and also validate it. How can i reuse the model fields, and also Validate the fields based on Scenario.

2

There are 2 best solutions below

0
On BEST ANSWER

i think you can reuse form model and can write custom validation rules in the form and for each action. for example. hari you just give a try like this...

class RegistrationForm extends CFormModel {

  public $login;
  public $password;
  public $email;
  public $mobile;

  public function rules() {
    return array(
      array('login,password','loginValidator','on'=>'login'),
      array('login,password,email,mobile','registerValidator','on'=>'register')
    );
  }

  public function loginValidator() {
    dummyfunc($this->login,.....);
  }

  public function registerValidator() {
    dummyfunc($this->login,.....);
  }

}

Controller part:

$formModel = new RegistrationForm('login');
$formModel->attributes = $_POST['RegistrationForm'];
if($formModel->validate()) {
  #..........;
} else {
  #..........;
}

have a nice day!!!

0
On

It is better to use a user module.

This is an example of the directory structure of a user module:

protected/modules/user/
    controllers/
        LoginController.php
        LogoutController.php
        RegisterController.php
        ...
    models/
        Login.php
        Register.php
        ...
    views/
        user/
            login.php
            register.php
            ...

The directory structure of yii-user might be useful.