Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP Pagination: how can I sort by multiple columns to achieve "sticky" functionality?

I see that this paginate can't sort two columns at the same time ticket is still open, which leads me to believe that what I'm trying to do is not possible without a workaround. So I guess what I'm looking for is a workaround.

I'm trying to do what many message boards do: have a "sticky" function. I'd like to make it so that no matter which table header link the user clicks on to sort, my model's "sticky" field is always the first thing sorted, followed by whatever column the user clicked on. I know that you can set $this->paginate['Model']['order'] to whatever you want, so you could hack it to put the "sticky" field first and the user's chosen column second. The problem with this method is that pagination doesn't behave properly after you do it. The table header links don't work right and switching pages doesn't work right either. Is there some other workaround?

like image 731
Nick Avatar asked Dec 11 '12 23:12

Nick


1 Answers

User ten1 on the CakePHP IRC channel helped me find the solution. I told him that if he posted the answer here then I would mark it as the correct one, but he said I should do it myself since he doesn't have a Stack Overflow account yet.

The trick is to inject the "sticky" field into the query's "order" setting using the model's "beforeFind" callback method, like this:

public function beforeFind($queryData) {
    $sticky = array('Model.sticky' => 'DESC');

    if (is_array($queryData['order'][0])) {
        $queryData['order'][0] = $sticky + $queryData['order'][0];
    }
    else {
        $queryData['order'][0] = $sticky;
    }

    return $queryData;
}
like image 87
Nick Avatar answered Nov 15 '22 11:11

Nick