PostHow to paginate search results in CakePHP

Question: How do I paginate data from a model based on a keyword submitted by a user?

I must say that it’s a little tricky because the Pagination component in CakePHP uses GET parameters to do it’s magic. That wouldn’t be a problem if I didn’t care about my URL structure but for SEO purposes extra GET parameters are unacceptable. The easiest way to pass the POST data from page to page without affecting my URL structure is by using Sessions. I’ll describe below my method of doing this.

I have a Search controller, SearchesController, that handles the search logic. To implement my example just create a controller named searches_controller.php in your /app/controller folder and paste the following code into it.

<?php
App::import('Sanitize');
class SearchesController extends AppController {
 
	var $name = 'Searches';
	var $uses = array('Post');
	var $paginate = array('limit' => 20);
 
	function display() {
		Configure::write('debug', 0);
		if(!empty($this->data)) {
			Sanitize::clean($this->data);
			$searchkey = $this->Session->read('Search.searchkey');
			if(empty($searchkey)) {
				$this->Session->write('Search.searchkey', $this->data['Search']['searchkey']);
			}
			if($this->data['Search']['searchkey'] != $this->Session->read('Search.searchkey')) {
				$this->Session->delete('Search.searchkey');
				$this->Session->write('Search.searchkey', $this->data['Search']['searchkey']);
			}
		}
		$options = array("MATCH(Post.title, Post.body) AGAINST('{$this->Session->read('Search.searchkey')}' IN BOOLEAN MODE)");
		$this->set('results',$this->paginate('Post', $options));
	}
}
?>

The code is pretty self explanatory, but I’ll go over it quickly just to make sure we’re on the same page. After we check for user submitted data and we clean it up, we check for a Session variable from a previous search. If it doesn’t exist we initiate a Session variable in which we hold the user’s keyword. Then we check if the keyword in our Session variable is the same with the one submitted by the user and update the Session variable if it isn’t.

After we set the Session variable we are ready set the conditions for the search operation. I choose the Match Against instructions for this search but you can use the Like or other type of comparison for your search. The we set the view variable using the paginate method. Note that you must create the appropriate views to render the results.

I believe that this is the simplest way of handling this type of situation and I hope you find it useful.

Happy baking.




Related posts

coded by nessus
I Disclose

Stay Connected

Subscribe to RSS Feed

Subscribe to RSS Feed

Follow me on Twitter

Follow me on Twitter

Subscribe via e-mail

Subscribe via e-mail


Post your comment

Leave a Reply