前台模型,只需要三个输入字段,做个简单的验证,也可以复杂些
<?php namespace app\models; use yii\base\Model; use app\models\User; /** * 前台模型更简单一些 * */ class SetPswdForm extends Model { public $oldpswd; public $newpswd; public $repeat; public function rules(){ return [ [['newpswd', 'oldpswd'], 'required'], [['newpswd', 'oldpswd'], 'string', 'min' => 4], ['repeat','compare','compareAttribute'=>'newpswd','message'=>'两次输入的密码不一致'], ]; } public function attributeLabels(){ return [ 'oldpswd' => '原密码', 'newpswd' => '新密码', 'repeat'=>'重复密码', ]; } }
视图也就一个简单的ActiveForm
<?php use yii\helpers\Html; use yii\bootstrap\ActiveForm; $this->title = '修改密码'; ?> <div class="row"> <h1><?= Html::encode($this->title) ?></h1> <div class="col-md-6"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'oldpswd')->passwordInput(['maxlength' => true]) ?> <?= $form->field($model, 'newpswd')->passwordInput(['maxlength' => true]) ?> <?= $form->field($model, 'repeat')->passwordInput(['maxlength' => true]) ?> <div class="form-group"> <?= Html::submitButton('确认修改', ['class' =>'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> </div> </div>
这次把控制器写的有些复杂了,主要是用登录的模型去模拟登录,然后判断旧密码是否正确,如果正确再去修改新的密码
public function actionReset() { if(Yii::$app->user->isGuest) { return $this->goHome(); } $model= new SetPswdForm(); if( $model->load(Yii::$app->request->post()) ){ $lg = new LoginForm(); $lg->username = Yii::$app->user->identity->username; $lg->password = $model->oldpswd; if($lg->login()){ $user= User::findOne(yii::$app->user->identity->id); if($model->newpswd == $model->repeat){ $user->setPassword($model->newpswd); $user->removePasswordResetToken(); if( $user->save() ){ Yii::$app->user->logout(); return '密码修改成功,请重新登录'; } }else{ return '新密码两次输入不相同'; } }else{ return '原密码错误'; } } return $this->render('reset', ['model'=>$model]); }
后面再继续研究下,如果更安全优雅的去修改密码。