Yii2: Filtering Gridview with Combobox and Pjax Technique

gridviewSaya tidak akan membuat intermezzo yang panjang, intinya kita akan membuat filter data pada gridview base on combobox.

1. Asumsi, kita punya 2 tabel

tb_employee
========
id
name
group_id

tb_group
=====
id
name

2. Generate CRUD tabel Empoyee via Gii
3. Tambahkan Combobox pada view index atau tabel list Employee

<?php
$data = ArrayHelper::map(\app\models\Group::find()->all(), 'name', 'name');
?>
<?= Html::dropDownList('group', null, $data,['prompt'=>'- select group -','class'=>'form-control']) ?>

4. Hubungkan combobox tersebut dengan Gridview, jadi ketika nilai combobox dipilih maka Gridview akan reload dengan parameter data dari combobox, kalau demikian.. kita butuh javascript disini.. dan untuk melakukannya.. Yii2 merekomendasikan tools Jquery Pjax, dan Alhamdulillahnya, Pjax udah include by default di Yii2..

5. Bungkus Gridview dengan Pjax, saya kasih id pjax-gridview

<?php Pjax::begin(['id' => 'pjax-gridview']) ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'tableOptions' => [
    	'class' => 'table table-striped table-bordered table-condensed table-hover table-mini',
    ],
    'showHeader'=> true,
    'columns' => [
    	...
    	...
    ],
]); ?>
<?php Pjax::end() ?>

6. Tambahkan fungsi untuk mereload Gridview ketika combobox di pilih.. maka kita bisa gunakan event onchange pada combobox dan gunakan fungsi pjax reload.

<?= Html::dropDownList('group', null, $data,['prompt'=>'- select group -','onchange'=>'
	$.pjax.reload({
		url: "'.Url::to(['index']).'?EmployeeSearch[group_id]="+$(this).val(),
		container: "#pjax-gridview",
		timeout: 1000,
	});
','class'=>'form-control']) ?>

7. Pastikan EmployeeSearch seperti ini, lihat artikel saya sebelumnya

public function rules()
{
    return [
        [['id'], 'integer'],
        [['name','group_id'], 'safe'],
    ];
}

public function search($params)
{
    $query = Employee::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $dataProvider->query->joinWith('group');

    $query->andFilterWhere([
        'id' => $this->id,
        //'group_id' => $this->group_id,
    ]);

    $query->andFilterWhere(['like', 'tb_employee.name', $this->name])
          ->andFilterWhere(['like', 'tb_group.name', $this->group_id]);

    return $dataProvider;
}

8. Selesai.. keep smile..

CMIIW

Jangan lupa pada view index, gunakan use2 berikut :)

use yii\helpers\ArrayHelper;
use yii\widgets\Pjax;
use yii\helpers\Url;

Tags:,
12 Comments
  1. Gemilang Permata
  2. Hafid Mukhlasin
  3. Novi Indra
    • Hafid Mukhlasin
  4. Gemilang Permata
  5. Sutrisno
  6. Muhammad Ramdhani
  7. Dhiar Praditya
  8. Muhammad Ramdhani
  9. Budiyanto

Leave a Reply

Your email address will not be published. Required fields are marked *