How does Gii default gridview sort work?

I’m trying to understand how the Gridview sorts, but I can’t find where in the code it’s doing it. I see that the controller calls the model’s search function with the query parameters, but where in this search function does the sort happen? I’ve searched this forum and found plenty of discussions about adding related columns to the sort, which I do want to do, but first I want to understand how it works “out of the box”, and can’t find any tutorials just about that.

Here’s my search function, which I think is pretty much as Gii generated it:

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

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
		   'sort' => [ 'defaultOrder' => [
			           'lastName' => SORT_ASC,
				   'firstName' => SORT_ASC
			           ]
		              ]       
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    // grid filtering conditions
    $query->andFilterWhere(['pkPersonID' => $this->pkPersonID,])
        ->andFilterWhere(['like', 'lastName', $this->lastName])
        ->andFilterWhere(['like', 'lastName', $this->lastName])
        ->andFilterWhere(['like', 'email', $this->email])
        ->andFilterWhere(['like', 'phone', $this->phone])
        ->andFilterWhere(['like', 'phoneExt', $this->phoneExt])
        ->andFilterWhere(['like', 'address1', $this->address1])
        ->andFilterWhere(['like', 'address2', $this->address2])
        ->andFilterWhere(['like', 'city', $this->city])
        ->andFilterWhere(['like', 'state', $this->state])
        ->andFilterWhere(['like', 'zipcode', $this->zipcode]);

    return $dataProvider;
}

Is it in the sort argument of the ActiveDataProvider constructor? But that looks like it only specifies a default. Where does the current sort parameter actually get applied to the data provider? I don’t see it, but it works nonetheless!

Here, I guess
https://www.yiiframework.com/doc/api/2.0/yii-data-activedataprovider#prepareModels()-detail

1 Like

But I don’t see a call to prepareModels in my code anywhere. I looked explicitly in the PersonSearch model, the Person model, and the PersonController, and also searched my entire project (Apache NetBeans IDE).

Check the source code of yii\data\BaseDataProvider which is the base class of yii\data\ActiveDataProvider.

When you (or, more precisely, your GridView widget) want to show the models, you will get them via the models attribute of the data provider. It is done through getModels() getter method which calls prepare() method where prepareModels() will be called when necessary.