DataProvider default sort SQL error

I have the following simple code:


$dataProvider = new ActiveDataProvider([

            'query' => Jobs::find(), 

            'sort'=> ['defaultOrder' => ['active' => SORT_DESC]]

          ]);

Where Jobs - is ActiveRecord model, ‘active’ - is DB column.

When passing this provider to GridView I get the following error:

Seems like a bug in the framework… Or am I missing something?

Does commenting out "sort" part help?

samdark, yes, without ‘sort’ everything works.

And one more thing. If I do like this: ‘query’ => Jobs::find()->orderBy(‘active DESC’). Then the default order is correct without ‘sort’ parameter. But in that case GridView sorting doesn’t work by ‘Active’ column. But as I understand this is not a bug, and the $query sorting has higher priority. Or not?

Probably the following will work as expected.




$dataProvider = new ActiveDataProvider([

    'query' => Jobs::find(), 

    'sort'=> [

        'attributes' => [

            'active',

            '...',

        ],

        'defaultOrder' => [

            'active' => SORT_DESC]

        ],

    ]);



IIRC, the attributes used in ‘defaultOrder’ property must be present in ‘attributes’ property.

1 Like

softark, could you explain what ‘attributes’ are for? With your suggestion the default sorting really applies, but the client-side sorting gets disabled (column headers become not clickable and manual inserting of sort GET parameters doesn’t make any effect).

The things are getting even more strange. I brought the project to home and the same code behaves in a differect way.


'sort'=> ['defaultOrder' => ['active' => SORT_DESC]]

Gives another error:

Try adding all of the attributes that are used in the header.

http://www.yiiframework.com/doc-2.0/yii-data-sort.html#$attributes-detail

[EDIT]

IIRC, "attributes" could be null when you would be satisfied with the default construction of the sort object. But you need to list all the attributes explicitly when you want to configure "defaultOrder".

Thanks for the explanations! But this didnt help. Whichever attributes I list, the client sorting remains disabled.

That’s strange. Could you share the relevant code?

I found what was the problem. As it often happens, the problem was hidden in a place where I didn’t search for it :)

Attributes turned out to be case-sensitive. I usually name DB columns in lower case, but this time some columns’ names were in upper case. So everything I need to do is replace ‘active’ with ‘ACTIVE’ :lol: