Insert, Update And Change Password In Yii Model

This tutorial will help you to understand “how to handle password field in yii”. I used scenario concept to change password.
So the rule of models was configured based on scenario concept of yii framework.It was working fine for me.

In Model.php Rules

public function rules()
{
    return array(
        array('username, password,confirmpassword',
                    'required', 'on'=>'insert'),

        array('username, password,confirmpassword', 
                    'required', 'on'=>'updateuser'),

        array('password,confirmpassword',
                    'required', 'on'=>'changepassword'),

            array('password', 'compare', 'compareAttribute' =>'confirmpassword',
                                'on'=>'insert,changepassword'),
            
           array('password','passwordalphanumeric',
                                'on'=>'changepassword'),    
}

public function passwordalphanumeric($attribute_name,$params){
    if(!empty($this->password)){
       if (preg_match('~^[a-z0-9]*[0-9][a-z0-9]*$~i',$this->password)) {
            // $subject is alphanumeric and contains at least 1 number
       } else {   // failed
           $this->addError($attribute_name,'Enter password with digits');
       }        
    }
}

Controller.php With Scenario

<?php
public function actionChangepassword($id){
        $userid=Yii::app()->user->getId();
        if($userid==$id){    
            $model=$this->loadModel($id);
            $model->scenario='changepassword';
            if(isset($_POST['User']))
            {
              $model->attributes=$_POST['User'];
              if($model->validate()){
                $model->password=sha1($model->password);
                $model->confirmpassword=sha1($model->confirmpassword);
                if($model->save())
                    $this->redirect(array('view','id'=>$model->userid));
                }
            }
            $model->password='';
            $model->confirmpassword='';
            $this->render('changepassword',array(
            'model'=>$model,  ));
        }
        else{
            Yii::app()->request->redirect('admin');
        }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *