article

Monday, May 16, 2011

Cakephp Custom group by pagination and a calculated field

Cakephp Custom group by pagination and a calculated field

Example of how to use the CakePHP paginator helper with the group by condition. this is from the original article from http://wiltonsoftware.com/posts/view/custom-group-by-pagination-and-a-calculated-field




In the Controller
1
<?<br>var $helpers = array('Paginator');<br>var $paginator = array('limit' => 20);<br><br>function admin_index($filter=null) {<br> $conditions = array();<br> $this->Comment->recursive = 0;<br> if ($filter == 'count') {<br>     $conditions = array('Comment.status = 0');<br>     $this->paginate['Comment'] = array(<br>         'fields' => array(<br>             'Comment.id', 'Comment.ip', 'Count(Comment.ip) as Count'<br>         ),<br>         'conditions' => array(<br>             'Comment.status = 0'<br>         ),<br>         'group' => array(<br>             'Comment.ip'<br>         ),<br>         'order' => array(<br>             'Count' => 'desc'<br>         )<br>     );<br>     $data = $this->paginate('Comment', $conditions);<br>  <br> } else {<br>     if ($filter == 'spam') {<br>         $conditions = array('Comment.status = 0');<br>     } else {<br>         $conditions = array('Comment.status > 0');<br>     }<br>     $this->paginate['Comment'] = array(<br>         'order' => array(<br>             'Comment.id' => 'desc'<br>         )<br>     );<br> }<br> $data = $this->paginate('Comment', $conditions);<br>}<br>?><br>

Model
1
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {<br>  $parameters = compact('conditions');<br>  $this->recursive = $recursive;<br>  $count = $this->find('count', array_merge($parameters, $extra));<br>  if (isset($extra['group'])) {<br>      $count = $this->getAffectedRows();<br>  }<br>  return $count;<br>}<br>

View
1
$paginator->options(array('url' => $this->passedArgs));<br>

Related Post