CakePHP Previous-Next Navigation

In programming, storing and retrieving data is a common process. CakePHP has many useful find type function which makes the process of data retrieval easier and practical. Usually, in index page, developer will list all records for that model. However, if the user navigates in details view (View.ctp) and need to go to the next or previous record, they need to navigate back to index and select the respective records. This tutorial will show how to use 'neighbor' find type to get a link to navigate to the next or previous records.

Assume that the table for this tutorial is ‘students’ where the PK is id (int)-AI. The table will automatically create an increment value such as 1,2,3,4 and so on. This ID will be read by the ‘neighbor’ find type. The controller should include the find neighbor as shown below:

public function view($id = null) {
	if (!$id) {
		throw new NotFoundException(__('Invalid Student'));
	}
	
	$student = $this->Student->findById($id);
	if (!$student) {
		throw new NotFoundException(__('Invalid Student'));
	}
	
	$this->set('student', $student);
     // fetching the record's neighbors 
	$neighbors = $this->Student->find('neighbors',array('field' => 'id', 'value' => $id));
	$this->set('neighbors', $neighbors);
}


Next, in your view.ctp, the link coding should exist as shown below:

<!-- Generate Previous and Next navigation -->
<p>
 <span>
<!-- Previous -->
<?php if(!empty($neighbors['prev'])){
	echo $this->Html->link(__('< Prev'), array('controller' => 'students', 'action' => 'view', $neighbors['prev']['Student']['id']), array('class'=>'btn btn-default', 'escape' => false)); 
} ?>
</span>

<span>
<!-- Next -->
<?php if(!empty($neighbors['next'])){
	echo $this->Html->link(__('Next >'), array('controller' => 'students', 'action' => 'view', $neighbors['next']['Student']['id']), array('class'=>'btn btn-default', 'escape' => false)); 
} ?>
</span>
</p>


The output should display the navigation link as shown below in view page.

That all. Happy coding :)