Search code examples
yii2paginator

Yii2: Easy way to render page size selector at the paginator


Is there any easy and native way to add html rendering of items per page selector to the paginator at the ListView ? I've looked through the docs:

  1. Yii widget listview
  2. Yii data pagination
  3. Yii widgets linkpager

Found everything I need, except rendering the page size selector. This is a bit strange, as this is a very common feature.


Solution

  • No there were no native way to do this, you can create your own or use this one:

    Define in your model filter:

        class YOUR_CLASS_FILTER extend YOUR_MODEL
           
        
            ...
               public $pagesize; // Property pagesize.
               const ITEMS_PER_PAGE_INIT = 12; // Initial items per page
               ...
            
               //Add or edit this in the same model `search` method:
               public function search($params){    
               ...
               $dataProvider = new ActiveDataProvider([
                        'query' => $query,
                        'pagination' => [
                            // this $params['pagesize'] is an id of dropdown list that we set in view file
                            'pagesize' => ($this->pagesize) ? $this->pagesize : self::ITEMS_PER_PAGE_INIT,
                        ],
                    ]);
               ...
               }    
               ... 
               public function rules()
                {
                    return [
                        ...
                        [['pagesize'], 'integer'],
                        ...
                    ];
                }
                ...
        /**
         * Return Static Array of elements per page
         * @return array
         */
        public static function itemsPerPage()
        {
            return array(
                12 => 12,
                24 => 24,
                48 => 48
            );
        }
    }
    

    This is how i implemented in view file:

    <?= $form->field($filter, 'pagesize')->dropDownList(
        $filter->itemsPerPage(),
        array(
          'id' => 'pagesize',
          'class' => 'form-control',
          'onchange' => 'this.form.submit()',
        ))->label("Items per page: ")
    ?>