L
L
Lander2015-09-01 17:12:09
Yii
Lander, 2015-09-01 17:12:09

Is there a good doc for GridView Yii2?

Good afternoon.
Understanding gridview. I would like to learn more (and more understandably) about the search in related tables. It doesn't work at all... :/
Advise the doc or good examples of how to set up filters considering relays.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander N++, 2015-09-01
@usdglander

It's just that you create a search method in the model that should return \yii\data\ActiveDataProvider
The model can be the one associated with the base or it can be a form model.
Do we need only attributes and validation from the model for the grid? search method, since we use the filled attributes in the + GridView method above the Header column displays an input

/**
     * @param $params
     * @param $group
     * @return \yii\data\ActiveDataProvider
     */
    public function search($params, $group = null )
    {
        $this->scenario = self::SCENARIO_SEARCH;          // когда у вас много правил по умолчанию следует использовать сценарии
  
    // базовый поиск
        $query = self::find();
        $dataProvider = new \yii\data\ActiveDataProvider([
            'query' => $query,
        ]);

    
  // Тут и нужный кастомные сценарии если базовая валидация мешает.
        if (!( $this->load($params) && $this->validate())) {
            return $dataProvider;
        }
    
  // применяем сортировку
        $dataProvider->setSort([
            'attributes' => [
                'id',
            ]
        ]);

    // добавляем к поиску условие например найти по диапазону даты.
        if(!empty($this->dateFrom) && !empty($this->dateTo)) {
            $query->andWhere('`hour_at` BETWEEN :dateFrom AND :dateTo', [
                ':dateFrom' => date('Y-m-d H:00:00', strtotime(trim($this->dateFrom))),
                ':dateTo' => date('Y-m-d H:59:59', strtotime(trim($this->dateTo))),
            ]);
        }
    
  // Добавляет условия если атрибуты нашей модели заполнены !=null
        $query->andFilterWhere([
            'stream_id'       => $this->stream_id,
            'country_id'      => $this->country_id,
            'browser'         => $this->browser,
            'os'                  => $this->os,
        ]);
        return $dataProvider;
    }

<?=GridView::widget([
        'dataProvider'    => $user->search(Yii::$app->request->get()),
        'filterModel' => $user,
        'columns' => [
            'id',
            'username' => [
                'attribute' => 'username',
            ],
            'email',
]]);?>

Search using Join is theoretically adding a condition to our activeQuery chunk of Sql query.
$query->join('left',Country::tableName(),'user.country_id='.Country::tableName().'.id');
        $query->andFilterWhere([
            Country::tableName().'.name' => $this->countryName
        ]);

Where countryName is a public property of the model class + declared in rules for example as a string

A
Alexander, 2015-09-02
@p0vidl0

There is a small description with an example and code here.

A
Alexander Makarov, 2015-09-03
@SamDark

https://github.com/yiisoft/yii2/blob/master/docs/g...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question