Search code examples
sortingcakephppaginationjquery-ui-sortablepaginator

CakePHP Pagination sort() on Related Models


I have two models: Plans and PlanDetails.

Relationship is: PlanDetails hasMany Plans. Plans belongTo PlanDetails.

In the PlanDetails view.ctp, I am pulling in related Plans.

I am trying to sort the Plans by ANY field (I've tried them all), and I cannot get it working. I assume I am overlooking something very simple.

Here is my base code:

PlanDetail >> view.ctp:

...foreach ($planDetail['Plan'] as $plan_edit) :
$class = null;
if ($i++ % 2 == 0) {
    $class = ' class="altrow"';
}...

<?php echo $this->Paginator->sort('Plan ID', 'Plan.id'); ?>...

...<?php echo $plan_edit['id']; ?>

plan_details_controller.php:

...function view($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid plan detail', true));
        $this->redirect(array('action' => 'index'));
    }
    $this->PlanDetail->recursive = 2; // To run the editable form deeper.
    $this->set('planDetail', $this->PlanDetail->read(null, $id));
    $this->set('plan', $this->paginate('Plan'));
}...

I should add, no errors are being thrown and the sort() arrows on the ID field are showing as expected, but the sort order DOES not change when clicked either way.


Solution

  • Here is what I did to solve this. Based on some helpful direction from johnp & tokes.

    plan_details/view.ctp:

    ...$i = 0;
    foreach ($plan as $plan_edit) : // note $plan here.
    }...
    

    In my plan_details_controller.php view action:

    $conditions = array("Plan.plan_detail_id" => "$id");
    $this->set('plan', $this->paginate('Plan', $conditions)); // note "plan" in the first argument of set (this is required to pass the results back to the view). Also. The $condition is set to return ONLY plans that match the plan_detail_id of id (on the plan_details table).
    

    And in my view, in order to get my results (because I changed the array name), I had to change the way I was getting the values to:

    $plan_edit['Plan']['modified'] // note I placed ['Plan'] in front of these calls as the array called for this to get the data...
    

    Well until the next problem! SOLVED.