yii2 curd

  1. controler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use Yii\models\Admin;

public function actionChangeEmail{
$this->layout = 'layout1';

$model = Admin::find()->where('adminuser=:user',[':user'=>Yii::$app->session['admin']['adminuser']])->one();

if( Yii::$app->request->isPost){
$post = Yii::$app0>request->post();
if($model->changeemail($post)){
Yii::$app->session->setFlash('info','update success!');
}
return $this->render('changeemail', ['model' => $model]);
}

}

  1. model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public function rules(){
return [
['adminuser', 'required', 'message'=>'username cannot be empty', 'on' => 'changeemail'],
['adminpass', 'required', 'message'=>'wordpass cannot be empty', 'on' => 'changeemail'],
['remember', 'bool', 'on' => 'login'],
['adminemial', 'email', 'message' => 'emial type error'],
['adminemial', 'unique', 'message' => 'email aready exists!'],
];

}


function changeemail($data){
$this->scenario = 'changeemail';
if($this->load($data) && $this->validate()){
return (bool)$this->updateAll(['adminemail'=>$this->adminemail], 'adminuser = :user',[':user'=> Yii::$app->user]);
}
return false;
}



  1. view
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
use yii\helpers\Html;
?>

<?=Url::to(['default/changeemail'])?>

<?php

if( Yii::$app->session->hasFlash('info')){
echo Yii::$app->session->getFlash('info');
}

$form= ActiveForm::begin([
'option' => ['class' => 'new_user_form'],
'fieldConfig' => [
'template' => '<div clas="span12 field-box">{label}{input}</div>{error}'
]
]);
?>

<?php echo $form->field($model, 'adminuser')->textInput(['class'=>'col-md-3', 'disabeled'=>true]); ?>
<?php echo $form->field($model, 'adminpass')->passwordInput(['class'=>'col-md-3']); ?>
<?php echo $form->field($model, 'adminemail')->textInput(['class'=>'col-md-3']); ?>

<div class="col-md-12 actions"?>
<?= Html::submitButton('create', ['class'=>'btn btn-success'])?>
<span>or</span>
<?= Html::resetButton('create', ['class'=>'btn btn-default'])?>
</div>

<?php ActiveForm::end();?>