Specific use of yii2's GridView and ActiveDataProvider

Reprinted to: https://www.cnblogs.com/xlz307/p/4187154.html

1. In the controller (take the list of User modules as an example):

first step:

use backend\models\User;
use yii\data\ActiveDataProvider;

Step 2:

public function actionIndex()
{
$model=new User();
$dataProvider = new ActiveDataProvider([
'query' => User::find()->orderBy('id'),//此处添加where条件时:'query'=>User::find()->where(['username'=>'lizi']);
]);
return $this->render('index', [
'model' => $model,
'dataProvider' => $dataProvider,
]);
}

2. In the view file:

first step:

use yii\helpers\Html;
use yii\grid\GridView;
use backend\models\User;

Step 2:

<?=
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[
'attribute' => 'username',
'content' => function($dataProvider){
return $dataProvider['username'];
},
],
'email:email',
[
'attribute' => 'created_at',
'format' => ['date', 'php:Y-m-d H:i:s'],
],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{view}{update}{password}{delete}',
'headerOptions' => ['width' => '128', 'class' => 'padding-left-5px',],
'contentOptions' => ['class' => 'padding-left-5px'],
'buttons' => [
'password' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-edit"></span>', $url, [
'title' => '修改密码',
'data-method' => 'post',
'data-pjax' => '0',
]);
},
],
],
],3. The running effect is as follows:
]); ?>
 

 

1. In the controller (take the list of User modules as an example):

first step:

use backend\models\User;
use yii\data\ActiveDataProvider;

Step 2:

public function actionIndex()
{
$model=new User();
$dataProvider = new ActiveDataProvider([
'query' => User::find()->orderBy('id'),//此处添加where条件时:'query'=>User::find()->where(['username'=>'lizi']);
]);
return $this->render('index', [
'model' => $model,
'dataProvider' => $dataProvider,
]);
}

2. In the view file:

first step:

use yii\helpers\Html;
use yii\grid\GridView;
use backend\models\User;

Step 2:

<?=
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[
'attribute' => 'username',
'content' => function($dataProvider){
return $dataProvider['username'];
},
],
'email:email',
[
'attribute' => 'created_at',
'format' => ['date', 'php:Y-m-d H:i:s'],
],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{view}{update}{password}{delete}',
'headerOptions' => ['width' => '128', 'class' => 'padding-left-5px',],
'contentOptions' => ['class' => 'padding-left-5px'],
'buttons' => [
'password' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-edit"></span>', $url, [
'title' => '修改密码',
'data-method' => 'post',
'data-pjax' => '0',
]);
},
],
],
],3. The running effect is as follows:
]); ?>
 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950760&siteId=291194637