How to display filtering model relationships on a GridView

I have two tables:

  • Country
  • Town

And have a relationship in the model.

Why doesn't the city have a filter?

public function getCountry()
{
    return $this->hasOne(Country::className(), ['id' => 'c_id']);
}

      

GridView

Picture:

GridView Image

+3


source to share


1 answer


You can do this by simply accessing it, for example:

'columns'=>[
   'country.columnName',
]);

      

In the model override function attributes()

:

public function attributes()
{
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['country.columnName']);
}

      

Add it to the rules:

public function rules()
{
     return [
         [['country.columnName'], 'safe'],
            // ... more stuff here
     ];
}

      

And in the method search()

add this to your Query

:

$query->andFilterWhere(['LIKE', 'country.columnName', $this->getAttribute('country.columnName')]);

      

=============================== OR ================== ============================================== ===== ==============

'columns' => [
   [
       'attribute' => 'countryFilter',
       'value' => function($model) {
           return $model->country->columnName;
        }
   ]
]);

      

To filter it, add a custom property to your search class:



public $countryFilter;

      

Add this to the rules:

public function rules()
{
     return [
         [['countryFilter'], 'safe'],
            // ... more stuff here
     ];
}

      

Add a method relation Query

in search()

:

->joinWith(['country'])

      

Then add filter media to Query

:

->andFilterWhere(['like', 'country.columnName', $this->countryFilter])

      

And to sort it, add:

$dataProvider->sort->attributes['countryFilter'] = [
                'asc'  => ['country.columnName' => SORT_ASC],
                'desc' => ['country.columnName' => SORT_DESC],
            ];

      

More information is available in the docs: Displaying and Sorting Relational Data

+1


source







All Articles