E
E
EVOSandru62017-09-14 09:07:55
Yii
EVOSandru6, 2017-09-14 09:07:55

How to sort dataProvider from _search file with ActiveForm in Yii2?

Good afternoon.
In my _search file I have a set for filtering the dataProvider in the ListView :

<?php $form = ActiveForm::begin([
          'options' => ['data-pjax' => true ],
        'method' => 'post',
    ]); ?>
<?= $form->field($model, 'id')->textInput([
        'type'=>'number'
    ]) ?>

<!-- рабочий price filter -->

<?= $form->field($model, 'name')->textInput() ?>
<?php ActiveForm::end(); ?>

In addition to filtering, I want to perform sorting.
I looked at the example of a regular grid in the Network, queries like:
Ascending:
products?sort=id
Descending:
products?sort=-id
I want to make a dropDown for sorting, the options for which are
1. name from a to z
2. name from z to and
3. price ascending
4. price descending
I assume that you need to create a new property in ProductsSearch and somehow insert its value into defaultSort . Or is there some more out of the box solution? Prompt please, who faced.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Bukharev, 2017-09-14
@EVOSandru6

Sorting is configured via the sort property date of the provider

$dataProvider = new ActiveDataProvider([
     'query' => $query,
     'sort'=> [
     'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
 ]);

Fill the attributes array with the parameters by which you need to sort, and then pass these parameters through the get query string in the form ...?sort=-name

B
Boris Korobkov, 2017-09-14
@BorisKorobkov

Already the de facto standard for sorting is clicking on the column heading. Why don't you like it out of the box? Why all these crutches with an extra select box?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question