A
A
akula222016-01-12 08:51:39
Yii
akula22, 2016-01-12 08:51:39

GridView and filter via hasOne?

I display the user_id field in the GridView

[
                'attribute' => 'user_id',
                'options' => array('width'=>'200px'),
                'value' => function ($model) { return $model->destinationUser->username; },
  ]

that is, through hasOne I get its name by id from the User table
public function getDestinationUser()
    {
        return $this->hasOne(\app\modules\user\models\User::className(), ['id' => 'user_id']);
    }

How can I now use the filter through the name?
Now the error The value of "user_id" must be an integer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2016-01-12
@akula22

Let's say you output the model Foo , the crud is generated using gii .
1. Add the $destinationUser property to the FooSearch class :

class FooSearch extends Foo
{
    public $destinationUser;
 
    public function rules()
    {
        return [
           ...
            ['destinationUser', 'safe'],
           ...
        ];
    }

2. In the FooSearch::search() method , add:
public function search($params)
{
    $query = Foo::find();

    $query->joinWith(['destinationUser']);
 
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
 
    // Для сортировки по User->username
    $dataProvider->sort->attributes['destinationUser'] = [
        'asc' => ['user.username' => SORT_ASC],
        'desc' => ['user.username' => SORT_DESC],
    ];
...
    $query->andFilterWhere([
        ...
    ])
    // Для поиска по имени
    ->andFilterWhere(['like', 'user.username', $this->destinationUser]);
 
    return $dataProvider;
}

3. Display the field like this:
[
    'attribute' => 'destinationUser',
    'options' => ['width'=>'200px'],
    'value' => 'destinationUser.username',
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question