Posts Tagged ‘Pagination’

27Mar

This is somewhat based off of the articles found in the bakery at cakephp.org; however, I will be expanding on those tutorials a bit. First of all, everyone likes fancy loading bars or spinners so here is a good site that will handle creating that for you: http://www.ajaxload.info/

One of my main challenges today was trying to properly narrow the results in each page depending on the category within the site I am located. This was not quite obvious. Another problem I had was trying to get data from other models. The first was more easily solvable. The second required me to use a request action. I am looking for a more elegant solution, but until then this gets the job done.

My controller is simple:


function cat($catId){
//Configure::write('debug', '2');
if(!$this->RequestHandler->isAjax()) {

}

$this->set('cat',$this->Event->EventCategory->find('first',array('conditions'=>array('EventCategory.id'=>$catId),'fields'=>array('EventCategory.id','EventCategory.cat_name'))));
$this->set('catId',$catId);
$this->set('events', $this->paginate(null, array('Event.event_category_id' => $catId,'Event.event_date>=curdate()')));

if($this->RequestHandler->isAjax()) {
$this->viewPath = 'elements'.DS.'events';
$this->render('paging');
}
}

The important line is where I set events with the call to paginate. This allows me to limit the results in the same why I would use find. Unfortunatly, unlike find it will not retrieve associated results.

View for cat


echo $javascript->link("prototype",false);
echo $javascript->link("scriptaculous/scriptaculous.js",false);
echo $javascript->link("columns/matching_columns",false);
//$paginator->options(array('update' => 'CatPaging', 'indicator' => 'LoadingDiv'));
?>
<div id="LoadingDiv" style="display: none;">
image('ajax-loader.gif'); ?></div>
<div id="CatPaging">
renderElement('events/paging'); ?></div>

elements/events/paging.ctp


$paginator->options(
array('update'=>'CatPaging',
'url'=>array('controller'=>'Events', 'action'=>'cat'),
'indicator' => 'LoadingDiv'));
?>
<div style="width: 100%; position: relative; float: left;">

// stuff here

</div>
<div style="margin: 15px 0pt; width: 100%; position: relative; text-align: center; float: left;">
prev('<<',array('url'=>$this->params['pass'])); ?> .
numbers(array('separator'=>' . ','url'=>$this->params['pass'])); ?> .
next('>>',array('url'=>$this->params['pass'])); ?></div>

I had to use the ‘url’ option and use $this->params[‘pass’] so that my url including the parameter transfered over to the pagination. Now I can use pagination within the categories of my events model! Not too bad.

I hope this helps someone! I was tweaking it for a few hours today. I hope it saves someone a little time.

Here it is in action: http://www.letswoosh.com/events/cat/1 (of course this is assuming I have at least 7events posted, right now there are 7. So tomorrow it may look like nothing is happening 🙁 )

Enjoy!

Share