CakePHP “public $paginate =” overwritten by action “$this->paginate =” Gotcha

Written by James McDonald

June 3, 2016

If you have a the following code

class PartsController extends AppController
{
    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        $this->paginate = [
            'contain' => ['Sections']
        ];
        $parts = $this->paginate($this->Parts);

        $this->set(compact('parts'));
        $this->set('_serialize', ['parts']);
    }

and then you define a public $paginate value in the class as thus:

class PartsController extends AppController
{

    
    public $paginate = [
        
            'order' =>
            [ 'Parts.sort_order' => 'asc'],
            'limit' => 5
    ];

 
    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
       // this will overwrite your previously set $paginate options
        $this->paginate = [
            'contain' => ['Sections']
        ];
        $parts = $this->paginate($this->Parts);

        $this->set(compact('parts'));
        $this->set('_serialize', ['parts']);
    }

You will find that your ‘order’ and ‘limit’ options are ignored because the $paginate property is being over written in the function index() method. As a work around so you can still globally configure your paginator use the += operator as follows:

class PartsController extends AppController
{

    
    public $paginate = [
        
            'order' =>
            [ 'Parts.sort_order' => 'asc'],
            'limit' => 5
    ];

 
    /**
     * Index method
     *
     * @return \Cake\Network\Response|null
     */
    public function index()
    {
        // using the += operator will add the options
        // to the previously defined $paginate property
        $this->paginate += [
            'contain' => ['Sections']
        ];
        $parts = $this->paginate($this->Parts);

        $this->set(compact('parts'));
        $this->set('_serialize', ['parts']);
    }

then the options you set within the index() method will be added to the globally defined public $paginate = []

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...