CakePHP: Paginating Model Multiple Times in the Same View

At work, I encountered a scenario where we needed to paginate a model over different sets of conditions. Multiple calls to $this->paginate() on the controller somewhat works, but the problem is generating the pagination links and determining which set of conditions is being paginated.

Let’s say, I have a Post belongsTo Category model relationship. I want to paginate post by Category in the same page.

Somewhere in the controller, I might have something like:

==

	
$phpCategoryPosts = $this->paginate('Post', array('Post.category_id' => 1));
$jsCategoryPosts = $this->paginate('Post', array('Post.category_id' => 2));

==

Then, to generate pagination links in the view, I might do something like:

==

// For PHP posts
if($this->Paginator->hasNext('Post')) {
    echo $this->Paginator->next('Next', array('model' => 'Post')); 
}
	
// For Javascript posts
if($this->Paginator->hasNext('Post')) {
    echo $this->Paginator->next('Next', array('model' => 'Post')); 
}

==

The paginator will just use the info from the most recent call to paginate() for that model in the controller. So if there are no PHP posts while there are 10 Javascript posts with 5 items per page, both PHP and Javascript posts will have a “Next” button. So how can CakePHP tell which is which?

My solution was to generate (on the fly) different models that I can use to paginate:

==

eval('class PhpPost extends Post {}');		
eval('class JavascriptPost extends Post {}');		
$this->loadModel('PhpPost');
$this->loadModel('JavascriptPost');
$phpCategoryPosts = $this->paginate('PhpPost', array('Post.category_id' => 1));
$jsCategoryPosts = $this->paginate('JavascriptPost', array('Post.category_id' => 2));

==

And in the view, just specify the which model to use:

==

// For PHP posts
if($this->Paginator->hasNext('PhpPost')) {
    echo $this->Paginator->next('Next', array('model' => 'PhpPost')); 
}
	
// For Javascript posts
if($this->Paginator->hasNext('JavascriptPost')) {
    echo $this->Paginator->next('Next', array('model' => 'JavascriptPost')); 
}

==

 

Comments

No comments so far.

Leave a Reply

 
(will not be published)
 
 
Comment
 
 

 

Resources