J
J
jekahm2016-05-25 23:38:19
Yii
jekahm, 2016-05-25 23:38:19

How data filtering works in Yii2?

Good day!
In office The Yii2 framework documentation has an article Data Widgets, one section of which describes how data filtering works . And as an example, the following is given. PostSearch model code:

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

class PostSearch extends Post
{
    public function rules()
    {
        // only fields in rules() are searchable
        return [
            [['id'], 'integer'],
            [['title', 'creation_date'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = Post::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        // load the search form data and validate
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        // adjust the query by adding the filters
        $query->andFilterWhere(['id' => $this->id]);
        $query->andFilterWhere(['like', 'title', $this->title])
              ->andFilterWhere(['like', 'creation_date', $this->creation_date]);

        return $dataProvider;
    }
}

But I can't understand exactly how additional filtering settings get into the $dataProvider variable ( $query->andFilterWhere ...), if $query had already been passed in the ActiveDataProvider parameters before and its value at that time was equal to Post:: find() ?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
L
latteo, 2016-05-26
@latteo

$query is an object, it is passed by reference
$query->andFilterWhere - changes its properties
And the request to the database occurs by calling one of the $dataProvider methods: getModels(), getTotalCount(), etc
For example, in the case of GridView https:// github.com/yiisoft/yii2/blob/2.0.8/framewo...

M
Maxim Timofeev, 2016-05-25
@webinar

You press the filter button, a query is generated that affects the result. Namely here:

if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

also note that this is a Search model that is inherited from the regular

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question