Sorting related HABTM Model data using CakePHP Paginator Helper

I was gazing at my deformed reflection in the golden ball hanging from the Christmas tree while thinking of one of the client requests we received today. In all the times CakePHP helped me get things done quickly and legit. This time I believe I will have to do some extra work from my side. The request is to have the related Appointments to the Client model all listed in a table with sortable headers. Not a big deal except that the Client model has a HABTM relationship with the appointment. I wanted so much to use the paginator helper function $paginator->sort with all the automagic passing of parameters, while keeping the controller skinny as possible. After few pr in the controller and view and two sips of Merlot I found the quick and not so bad solution.

From the controller:

  1. <?php
  2. 	var $helpers = array('Html', 'Form', 'Field', 'Javascript', 'Paginator');
  4. 	function view_client_notes($id = null) {
  5. 		$this->Client->Behaviors->attach('Containable');
  6. 		if(empty($this->params['named']['sort'])) {
  7. 			$this->params['named']['sort'] = 'time';
  8. 		}
  9. 		if(empty($this->params['named']['direction'])) {
  10. 			$this->params['named']['direction'] = 'DESC';
  11. 		}
  13. 		$this->Client->contain(array('Appointment' => array(
  14. 			'order' => "Appointment.{$this->params['named']['sort']} {$this->params['named']['direction']}"
  15. 		)));
  16. 		$this->set('client', $this->Client->read(null, $id));
  17. 		$this->paginate('Appointment', array('' => 0));
  18. 	}
  19. ?>

Note adding the Paginator helper to the list of helpers. In the view:
  1. 	<th><?php echo $paginator->sort('Note', 'client_note');?></th>
  2. 	<th><?php echo $paginator->sort('Appointment', 'appointment_type');?></th>
  3. 	<th><?php echo $paginator->sort('Time', 'time');?></th>

Pagination sorting options are sent in the $this->params['named']['sort'] and $this->params['named']['direction'], in case they are empty, just put the defaults you want to use for sorting.

Merry Christmass Baking!