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 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Clear HSTS Settings in CHrome

Open chrome://net-internals/#hsts enter the domain in the query field and click Query to confirm it has HSTS settings...

Ubuntu on Hyper-v

It boils town to installing linux-azure # as root or sudo apt-get update apt-get install linux-azure...