mumunotes

  • Home
  • Contact Us

Thursday, 11 June 2015

Change password with validation and repeat password on Yii2

 mumunotesss     14:39     Yii, Yii2     No comments   



Hello everybody. I could not post an article because I didn't have new knowledge to share. Ok, this day I will share about "Change password with validation and repeat password on Yii2".
I still using the yii2basic applicaton. If you don't have it, please refer this for develop it.
If you have yii2basic application, then you must create PasswordForm.php file and save it in the models directory. Please add the code bellow.
<?php
    namespace app\models;
   
    use Yii;
    use yii\base\Model;
    use app\models\Login;
   
    class PasswordForm extends Model{
        public $oldpass;
        public $newpass;
        public $repeatnewpass;
       
        public function rules(){
            return [
                [['oldpass','newpass','repeatnewpass'],'required'],
                ['oldpass','findPasswords'],
                ['repeatnewpass','compare','compareAttribute'=>'newpass'],
            ];
        }
       
        public function findPasswords($attribute, $params){
            $user = Login::find()->where([
                'username'=>Yii::$app->user->identity->username
            ])->one();
            $password = $user->password;
            if($password!=$this->oldpass)
                $this->addError($attribute,'Old password is incorrect');
        }
       
        public function attributeLabels(){
            return [
                'oldpass'=>'Old Password',
                'newpass'=>'New Password',
                'repeatnewpass'=>'Repeat New Password',
            ];
        }
    }
The above code is model class for implement to change password form. Let's create changepassword.php file in views/site directory.
It use to make changepassword view. It show change password form to end users. Please add the code bellow.
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

$this->title = 'Change Password';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="site-changepassword">
    <h1><?= Html::encode($this->title) ?></h1>
   
    <p>Please fill out the following fields to change password :</p>
   
    <?php $form = ActiveForm::begin([
        'id'=>'changepassword-form',
        'options'=>['class'=>'form-horizontal'],
        'fieldConfig'=>[
            'template'=>"{label}\n<div class=\"col-lg-3\">
                        {input}</div>\n<div class=\"col-lg-5\">
                        {error}</div>",
            'labelOptions'=>['class'=>'col-lg-2 control-label'],
        ],
    ]); ?>
        <?= $form->field($model,'oldpass',['inputOptions'=>[
            'placeholder'=>'Old Password'
        ]])->passwordInput() ?>
       
        <?= $form->field($model,'newpass',['inputOptions'=>[
            'placeholder'=>'New Password'
        ]])->passwordInput() ?>
       
        <?= $form->field($model,'repeatnewpass',['inputOptions'=>[
            'placeholder'=>'Repeat New Password'
        ]])->passwordInput() ?>
       
        <div class="form-group">
            <div class="col-lg-offset-2 col-lg-11">
                <?= Html::submitButton('Change password',[
                    'class'=>'btn btn-primary'
                ]) ?>
            </div>
        </div>
    <?php ActiveForm::end(); ?>
</div>
And then you must change SiteController.php file in controllers directory. Please following this code and add to your SiteController.php
use app\models\PasswordForm;
use app\models\Login;

class SiteController extends Controller{
    public function behaviors(){
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout','changepassword'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    //other code default

    public function actionChangepassword(){
        $model = new PasswordForm;
        $modeluser = Login::find()->where([
            'username'=>Yii::$app->user->identity->username
        ])->one();
     
        if($model->load(Yii::$app->request->post())){
            if($model->validate()){
                try{
                    $modeluser->password = $_POST['PasswordForm']['newpass'];
                    if($modeluser->save()){
                        Yii::$app->getSession()->setFlash(
                            'success','Password changed'
                        );
                        return $this->redirect(['index']);
                    }else{
                        Yii::$app->getSession()->setFlash(
                            'error','Password not changed'
                        );
                        return $this->redirect(['index']);
                    }
                }catch(Exception $e){
                    Yii::$app->getSession()->setFlash(
                        'error',"{$e->getMessage()}"
                    );
                    return $this->render('changepassword',[
                        'model'=>$model
                    ]);
                }
            }else{
                return $this->render('changepassword',[
                    'model'=>$model
                ]);
            }
        }else{
            return $this->render('changepassword',[
                'model'=>$model
            ]);
        }
    }
}
Ok, it's time to trial this application. You must login with already user and access this url in your browser "http://localhost/tutorial/web/index.php?r=site%2Fchangepassword"

Try with incorrect your old password and repeat new password. The application displaying error old password like pictures bellow.



Now try with correct your old password and repeat new password. The application displaying information like piciture bellow and your password changed.

So my post about "Change password with validation and repeat password on Yii2"  on this day. I hope that help you all to learning Yii2 Framework. Tnank...:D

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

About Me

mumunotesss
View my complete profile

Popular Posts

  • Change password with validation and repeat password on Yii2
    Hello everybody. I could not post an article because I didn't have new knowledge to share. Ok, this day I will share about "...
  • Import Data from CSV File to Database Without Extension in Yii2
    Hello everybody, Assalamualaikum Wr. Wb. Nearly 1 month I don't publish article. Now, I publish an article about " Import Data fro...
  • Membuat login Yii2 dengan Database
    Selamat pagi guys. Sorry beberapa hari kamaren sibuk. Jadi belum sempet update blog lagi. Mumpung kali ini sempet, hari ini mau berbagi te...
  • Membuat fungsi CRUD dengan Gii Yii2
    Selamat pagi guys. Setelah kemaren kita membuat login dari database, hari ini kita akan membuat CRUD (create, read, update, delete) dengan ...

Blog Archive

  • ▼  2015 (16)
    • ►  November (1)
    • ►  September (1)
    • ►  August (1)
    • ▼  June (8)
      • Upload File or Image on Yii2
      • Implementation google reCAPTCHA on Yii2 Applicati...
      • Implementation Captcha on Yii2
      • Change password with validation and repeat passwor...
      • Membuat Alert atau Notifikasi di Yii2
      • ACF (Access Control Filter) Yii2 dengan Role dari ...
      • Membuat fungsi CRUD dengan Gii Yii2
      • Membuat login Yii2 dengan Database
    • ►  May (5)

Translate

Copyright © mumunotes
Distributed By My Blogger Themes | Blogger Theme By NewBloggerThemes