-
-
----2018-11-11 15:26:33
Yii
----, 2018-11-11 15:26:33

Teach how to form a filter in a GridView to a related model?

Hello again!
Tell me (I would even say - TEACH!) the solution to this problem:
There is an Order table and there is a
standard connection for the Portfolio table:

public function getPortfolio()
    {
        return $this->hasOne(Portfolio::class, ['id' => 'portfolio_id']);
    }

In the GridView, I want to display in the filter exactly those Portfolios whose id are present in the portfolio_id column of the Order table
. At the moment, I wrote such a crutch in order/index.php
[
                'attribute' => 'portfolio_id',
                'headerOptions' => ['class' => 'col-md-1'],
                //'headerOptions' => ['width' => '50'],
                'format' => 'text',
                'filter' => Html::activeDropDownList($searchModel, 'portfolio_id', Portfolio::getNames(), // возвращаем ВСЕ портфели
                    ['class' => 'form-control', 'prompt' => 'Все']),
                'value' => 'portfolio.title'
            ],

in the Order table - there are orders for 2 portfolios out of 5 .. in dropdown - I see all 5 Portfolios ..
I want to understand the very principle of working with relationships .. I read the doc - everything seems to be clear .. but what exactly to do - no ...
I understand that you need to create a method in the Order model that will pull all the values ​​of the portfolio_id column and give them to me as an array (id - portfolio.title) ... Right?
Can you provide a specific example for this case?
It's just that in my other tables - approximately the same connections and the task will be repeated (only the names of the related tables will be different)..
Please do not judge strictly and do not laugh =).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-11-11
@stalkerxxl

In the gridView, set the option 'filterModel' => $searchModelfor the entire table.
What does Portfolio::getNames() return, just the names?
I would rewrite the filter parameters a little differently.

[
                'attribute' => 'id_portfolio',
                'headerOptions' => ['class' => 'col-md-1'],
                'format' => 'text',
                'filter' => Portpholio::getAllPortfolio(),
                'value' => 'portfolio.title'
            ],

The getAllPortfolio() method itself might look like this
public static function getAllPortfolio()
    {
        return ArrayHelper::map(self::find()->orderBy(['name' => SORT_ASC])->all(), 'id', 'name');
    }

In the search model, the query might look like this (also add a public property)
public $id_portfolio;

$query = Order::find()->with('portfolio');

$query->andFilterWhere('{{%portfolio}}.id' => $this->id_portfolio);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question