Yii v2 snippet guide

Comparing #207 with #208

Revision #208 was created by rackycz rackycz on Jul 3, 2020, 12:46:05 PM.

GridViev - Variable page size

Content

[...]
GridView cannot display DropDownList which could be used by the user to change the number of rows per page. You have to add it manually like this:

When you are creating a new model using Gii, you can select if you want to create the SearchModel as well. Do it, it is usefull for example in this situation. Then add following rows to the model:

```php
// file models/InvoiceSearch.php
 
 
use yii\helpers\Html; // add this row

class InvoiceSearch extends Invoice
[...]
// ...

//
aAdd followingthis functions:
public function getPageSizeDropDown($htmlOptions = [], $prefixHtml = '', $suffixHtml = '', $labelPrefix = '') {
return $prefixHtml . Html::activeDropDownList($this, 'pageSize',
[...]
}

    // Add this function:
 
public function getPageSizeDropDownID($prefix = '#') { return $prefix . Html::getInputId($this, 'pageSize'); }     // This function already exists, so change it:
 
public function search($params) { // .. $this->load($params);         
 
        // Add following rows:
if (!isset($this->pageSize)) { // Here we make sure that the dropDownLst will have correct value preselected $this->pageSize = $dataProvider->pagination->defaultPageSize; }         
 
$dataProvider->pagination->pageSize = (int)$this->pageSize;         
 
```

And then in your views/xxx/index.php use following:
[...]
'filterModel' => $searchModel,
'layout'=>'{summary}<br>{items}<br><div style="display:flex; background-color: #f9f9f9; padding: 0px 3rem;"><div style="flex-grow: 2;">{pager}</div><div style="align-self:center;">'.$pageSizeDropDown.'</div></div>',
'pager' => [ 'maxButtonCount' =>
320 ], 'filterSelector' => $searchModel->getPageSizeDropDownID(), // filterSelector is the core solution of this problem. It refreshes the grid. ```