Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Gridview case insensitive sortable column

Tags:

php

yii2

I use yii2 and I want to make gridview column 'description' sortable in a case insensitive way. There is my code:

$dataProvider = new ArrayDataProvider([
    'allModels' => $query->find(),
    'sort' => [
    'attributes' => ['name','description],
    ],
    'pagination' => [
    'pageSize' => $this->pageSize,
    ],
]);

When I click on column description to sort, it show like this:

  • Job Title
  • Doctor
  • Teacher
  • doctor
  • teacher

As you see it sort case sensitive I want to sort case Insensitive, how I can do that? Any idea?

like image 538
dejanKr Avatar asked Mar 07 '26 12:03

dejanKr


1 Answers

In order to sort rows of ArrayDataProvider in a case-insensitive way you should extend ArrayDataProvider itself, because internally it uses ArrayHelper::multisort and if you want it sort the way you want you have to pass SORT_STRING | SORT_FLAG_CASE as fourth argument to the method. By default its value equal to SORT_REGULAR constant.

Here the implementation:

<?php

namespace app\dataproviders;

use yii\helpers\ArrayHelper;

/**
 * Class ArrayDataProvider
 */
class ArrayDataProvider extends \yii\data\ArrayDataProvider
{

    /** @inheritdoc */
    protected function sortModels($models, $sort)
    {
        $orders = $sort->getOrders();
        if (!empty($orders)) {
            ArrayHelper::multisort(
                $models,
                array_keys($orders),
                array_values($orders),
                SORT_STRING | SORT_FLAG_CASE
            );
        }

        return $models;
    }
}

And after it use the extended class instead of \yii\data\ArrayDataProvider

Example of usage:

$dataProvider = \app\dataproviders\ArrayDataProvider([
    'allModels' => $query->find(),
    'sort' => [
        'attributes' => ['name','description'],
    ],
    'pagination' => [
    'pageSize' => $this->pageSize,
    ],
]);
like image 196
Akmal Avatar answered Mar 09 '26 04:03

Akmal