Implement filtering and sorting ListView

Hello. I want allow users to sort posts list and filter by categories, text, date and few others. Currently I implemented ajax submitting of FilterForm model, but this only works for first page, because when I click on pagination, there is request to current url without any additional params, so ListView lost all filters. Probably I not explained it well, so look at images:

Changing page:

Maybe there is way to attach FilterForm model to ListView pagination or I should implement filtering and sorting in other way?

Just let Gii generate CRUD pages for you. You’ll find exactly what you want in the index page. Although it uses GridView by default, you can optionally use ListView instead. (Change “Widget Used in index Page” from GridView to ListView in the generator’s settings.)

http://www.yiiframework.com/doc-2.0/guide-start-gii.html#generating-crud

As a side note, the form for searching should use ‘GET’ method instead of ‘POST’. That’s what Gii generated index page is doing for its search form.

Following the Gii code, now I use DataProvider and SearchModel to get results. I have one question, how I can accomplish this:

where filters, sorter are outside ListView and sorter is dropdown list?

Well, it looks a bit tough, because the sorter should be placed together with the search form rather than with the ListView.

I’m sorry, I don’t have a quick answer to it, although I believe it’s possible somehow.

The following will add a LinkSorter widget between the search form and the ListView in your index page.




/* index.php view script */

    ...

    <?php echo $this->render('_search', ['model' => $searchModel]); ?>

    <?= LinkSorter::widget([

        'sort' => $dataProvider->sort,

    ]) ?>

    ...

    <?= ListView::widget([

        'dataProvider' => $dataProvider,

        ...

    ]) ?>



I think you can wrap the form and the sorter in a div that is collapsible.

I know that you want the sorter to be a dropdown. Google it and I hope you’ll find some nice extensions.

https://github.com/RezaSR/yii2-ButtonDropdownSorter, for example.