How to sort GridView by custom rule?

Now the column is built this way:




[

  'attribute' => 'vocabulary_id',

  'format' => 'raw',

  'value' => function ($model) {

    return Html::a(

      Html::encode($model->vocabulary->name),

      ['vocabularies/update', 'id' => $model->vocabulary_id]

    );

  }

],



The problem is that the column is sorted by attribute value (i.e. the ID of vocabularies) but not the presented text in cells.

What should I do to make the column be sorted by a custom callback (like the php usort function takes) or something like that?

$sort_attr = ‘?sort=sort_attr’;

$sort_attr_class = ‘’;

if(isset($_GET[‘sort’]) && $_GET[‘sort’] == ‘sort_attr’) {

$sort_attr = ‘?sort=-totalsession’;

$sort_attr_class = ‘asc’;

}

if(isset($_GET[‘sort’]) && $_GET[‘sort’] == ‘-sort_attr’) {

$sort_attr_class = ‘desc’;

}

In GRID view:

‘header’ => ‘<a class="’.$sort_attr_class.’" data-sort=“cat_name” href="’-PATH-’.$sort_attr.’">Sort ATTR</a>’,

Now in the controller with the help of query string you can easily manipulate the array.

Hope this hint might helps you!