3

Say I have a number of colored balls created at different times that I wish to display in a GridView.

  • Ball - id, color, created_at

Populated as:

1, red   , 2010-10-09
2, blue  , 2010-11-08
3, blue  , 2010-09-01
4, red   , 2010-06-15 

As a default I want the balls to be displayed newest first but I also want to be able to order the balls by color, so I set up the following search function in the BallSearch model:

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

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'attributes' => [
                'color',
                'created_at',
            ],
            'defaultOrder'=> ['created_at' => SORT_DESC]
        ],
    ]);

    return $dataProvider;
}

This works up to a point but when sorting by color, I understandably lose the newest first sorting. I'd really like this result:

2, blue  , 2010-11-08
3, blue  , 2010-09-01
1, red   , 2010-10-09
4, red   , 2010-06-15 

Unfortunately, if I put the newest first condition on the find query:

...
$query = Ball::find()->orderBy(['created_at' => SORT_DESC]);
...

It gets applied before the sort ordering and the results are no longer ordered by color primarily and the GridView ordering is ineffective.

Is there anyway to specify this underlying secondary ordering without concatting complicated conditions to each attribute order?

It seems to me that this is a common use case.

1 Answer 1

6

You could simply try :

'sort' => [
    'attributes' => [
        'color' => [
            'asc' => ['color' => SORT_ASC, 'created_at' => SORT_DESC],
            'desc' => ['color' => SORT_DESC, 'created_at' => SORT_ASC],
        ],
        'created_at',
    ],
    'defaultOrder'=> ['created_at' => SORT_DESC]
],

Read more about Sorting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.