Matthew Smart
Matthew Smart

Reputation: 1319

how to change grid view through Ajax? yii2

First of all i am working with yii2.0 framework.

Right, i have a gridview that pulls data from my database. It currently works and if i use any of the searches it will reload the page with the new data.

However i now have created some dropdownlist categories. Basically there are three tiers of categories , so a main category subcategory and child category. At the moment i have two ajax requests that will populate the sub and child category when the dropdownlist changes. (It populates the categories from my database).

Now i want the gridview to display the cases that are linked to the child categories. So when i choose my first category then choose my second and child category the gridview displays the content that relates to it.

At the moment my controller renders the searchModel + dataProvider for the grid view as seen below::

public function actionIndex()
{
    $searchModel = new CaseSearch();  
    $allCategory = Category::find()->all();

    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'allCategory' => $allCategory
    ]);
}

and in my view it displays the data with this::

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'case_id',
        'name',
        'judgement_date',
        'year',
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

How should i go about achieving this? should i create something _grid.php which i can then render from my view and send the ajax request there?

Upvotes: 2

Views: 6014

Answers (2)

arogachev
arogachev

Reputation: 33538

The simplest way to achieve this functionality is to wrap the GridView with built-in Pjax widget like so:

use yii\widgets\Pjax;

<?php Pjax::begin(); ?>

// Place GridView code here

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

From the js you can trigger form submit like that:

$('.grid-view-selector').yiiGridView('applyFilter');

If pjax is attached, content will be replaced dynamically without page reload.

Official docs:

Upvotes: 3

Colohanin Nik
Colohanin Nik

Reputation: 418

I would probably will use GridView $filterSelector. And add the selector for youre custom category dropDown. After you will need add category attribute for youre SearchModel. In final - wou will get the filter with youre custom field added to standart some

Upvotes: 1

Related Questions