1
votes

I'm using cakephp 2.5.6 and I want to display array in my view file. I try to put cakephp default pagination with this array, but it didn't work. Here is my example code

---'my_pages' controller-----

public function view(){
    //some other code
     $resultArray = $this->MyPages->getResults();
     $resultArray = $this->Paginator->paginate('resultArray');
     $this->set(compact('resultArray','rightPanel'));
}

and my view file

----- 'view.ctp' file ------
//some other code

foreach ($resultArray as $result){
   echo $result['subject'];
   echo $result['body'];
}

In my case this $resultArray have nearly hundred elements, and I want to put pagination on this page. So is it possible to use cakephp default pagination in this case ?? Thanks :)

1

1 Answers

1
votes

You need to implement cakephp custom pagination.

CakePHP uses two method to manage pagination queries, that are paginate and paginateCount, they are used to get page data and total record count respectively. To have pagination work with your custom queries, we will need to implement both above functions in our model file where you want to have pagination to work with custom queries. You can implement in your behavior file as well. Let’s see how we can have this implemented.

//in MyPages model add

public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {    
    $recursive = -1;

    // Mandatory to have
    $this->useTable = false;
    $sql = '';

    $sql .= "SELECT * FROM table_name limit ";

    // Adding LIMIT Clause
    $sql .= (($page - 1) * $limit) . ', ' . $limit;

    $results = $this->query($sql);

    return $results;
}
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {

    $sql = '';

    $sql .= "SELECT * FROM table_name";

    $this->recursive = $recursive;

    $results = $this->query($sql);

    return count($results);
}

Your controller file will look like below:

---'my_pages' controller-----

public function view(){
    // Do not forgot to set this, not sure why
    $this->MyPages->recursive = 0;
    // Setting up paging parameters
    $this->paginate = array('MyPages'=>array('limit'=>5));
    // Getting paginated result based on page #
    $this->set('resultArray', $this->paginate('MyPages'));
}

Note : MyPages should be MyPage, because Cakephp model name should be singular.

Your view file will look like below:

----- 'view.ctp' file ------
//some other code

foreach ($resultArray as $result){
  echo $result['subject'];
  echo $result['body'];
}

Also you can read the Pagination with Custom Queries in CakePHP