Roby Sottini
Roby Sottini

Reputation: 2265

Yii2: How to sort a GridView's column that doesn't belong to its model

I made a model and its CRUD using Gii from a table called vacations. Its index.php has a GridView with two columns called Column 1 and Column 3. Then I added a column called Person that come from a table called persons.

GridView

The problem is that the column Person is not sortable.

So I have this tables (column1_id and person_id are primary key of their tables):

vacations: column1_id, column3.
persons: person_id, person_name, column1_id.

Maybe I have to add something in the VacationsSearch file.

Upvotes: 0

Views: 77

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133410

essentially you should extend you search function for adding the query and sort for the related column

   $dataProvider->setSort([
       .....
          'your_related_column' => [
              'asc' => ['related_table.your_related_column' => SORT_ASC],
              'desc' => ['related_table.your_related_column' => SORT_DESC],
              'label' => 'Your Label'
          ]
      ]
  ]);

   .....

  // filter by country name
  $query->joinWith(['yor_relation' => function ($q) {
      $q->where('related_table.your_related_column LIKE "%' . $this->yourRelatedAttribute . '%"');
  }]);

for a wider explanation you can see the scenario 2 of this example http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

Upvotes: 1

Related Questions