控制器
public function actionPassword()
{
$model = new PasswordForm;
$request = Yii::$app->request;
$res=$model->load(Yii::$app->request->post());
var_dump($res);
if($request->isPost && $model->load(Yii::$app->request->post()) && $model->changePassword())
{
//echo "123";
Yii::$app->user->logout();
return $this->goHome();
}else{
return $this->render('modify-password',['model'=>$model]);
}
}
model
<?php
namespace frontend\models;
use Yii;
use yii\base\model;
use common\models\User;
class PasswordForm extends model
{
public $password;
public $pass1;
public $pass2;
public static function tableName()
{
return 'user';
}
public function changePassword()
{
$id = Yii::$app->user->id;
$admin= User::findIdentity($id);
$password = $admin->password_hash;
if(Yii::$app->getSecurity()->validatePassword($this->password, $password)){
if($this->pass1 == $this->pass2){
$newPass = Yii::$app->getSecurity()->generatePasswordHash($this->pass1);
$admin->password_hash = $newPass;
if($admin->save()){
return true;
}else{
return false;
}
}else{
Yii::$app->session->setFlash('contact','两次新密码不相等');
return false;
}
}else{
Yii::$app->session->setFlash('contact','旧密码错误');
return false;
}
}
}
视图
<?= Html::beginForm(['password'], 'post', ['enctype' => 'multipart/form-data']) ?>
<div class="pass">
<p class="pass-box">
<img src="<?=$baseUrl?>images/srmm.png" />
<!--<input type="password" name="old" placeholder="输入旧密码…" />-->
<?=Html::input('password','model[password]','',['placeholder'=>'输入旧密码…']) ?>
</p>
<!--<span>旧密码错误</span>-->
</div>
<div class="pass">
<p class="pass-box">
<img src="<?=$baseUrl?>images/srmm.png" />
<!--<input type="password" name="new" placeholder="输入新密码…" />-->
<?=Html::input('password','model[pass1]','',['placeholder'=>'输入新密码…']) ?>
</p>
<!--<span>新密码不符合</span>-->
</div>
<div class="pass">
<p class="pass-box">
<img src="<?=$baseUrl?>images/srmm.png" />
<!--<input type="password" name="old" placeholder="再次输入新密码…" />-->
<?=Html::input('password','model[pass2]','',['placeholder'=>'输入新密码…']) ?>
</p>
<!--<span>2次密码输入不一致</span>-->
</div>
</div>
<p class="btn">
<!--<button>保 存</button>-->
<?=Html::submitButton('保 存')?>
</p>
</div>
<?= Html::endForm() ?>
PasswordForm 中增加下面规则:
“
如果用了load, 建议在Form中使用 Html::activeTextInput 之类的方法