How to limit records per page from view using CakePHP 3

Place the following code in your view:

<div id="recperpage">
    <?=$this->Form->create(null, [
	'url' => ['controller' => 'mycontroller', 'action' => 'index'],
	'id'  => 'myformid',
    ])?>
	Records per page: <?=$this->Form->select('recperpageval', 
			[5=>5, 10=>10, 20=>20, 50=>50, 100=>100, 250=>250, 500=>500],
			['default' => 20, 'onchange'=>'onSelectSubmit("myformid")']
		)
	?>
    <?=$this->Form->end()?>
</div>

You will need this javascript code:

function onSelectSubmit(frmid)
{
    document.getElementById(frmid).submit();
}

Controller’s index action:

public function index()
{
    $limit = 20;
    if ($this->request->is('post')) 
    {
	if(in_array($this->request->data('recperpageval'), 
		[5, 10, 20, 50, 100, 250, 500]))
	{
		$limit = $this->request->data('recperpageval');
	}
    }
    $this->set('varname', 
	$this->Paginator->paginate(
	TableRegistry::get('Customers')->find(), ['limit'=>$limit]));
}
Categories: CakePHP, PHP Tags: , , ,
%d bloggers like this: