Showing posts with label limit. Show all posts
Showing posts with label limit. Show all posts

Tuesday, October 1, 2013

Grails pagination on a ArrayList

In my recent grails project, i needed to paginate on an array list, so I wrote a function and thought would share it with you all.

public List getFilteredList(int max, int offset) {
    max = Math.min(max ?: 25, 100)
    offset = (offset && offset > 0) ?: 0

    List names = getNames() //Loads the complete list
    int total = names.size()
    int upperLimit = findUpperIndex(offset, max, total)
    List filteredNames = names.getAt(offset..upperLimit)
    return filteredNames
}

private static int findUpperIndex(int offset, int max, int total) {
    max = offset + max - 1
    if (max >= total) {
        max -= max - total + 1
    }
    return max
}
So now if offset=20 and max=10, total = 28 so this will generate a list from 21st to 28th elements of the main list.

Saturday, June 1, 2013

YII CGridView with CActiveDataProvider customer limit and offset params

It is a CGridView example with CActiveDataProvider class:
<?php 
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    "itemsCssClass" => "table_design_1",
    "htmlOptions" => array(
        "class" => "div_design_1"
    ),
    'columns'=>array(
        array(
            'name'=>'family_name', 
            'header'=>'First name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->family_name,$data->id)'
        ),
        array(
            'name'=>'given_name', 
            'header'=>'Last name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->given_name,$data->id)'
        ),
        array(
            'class'=>'CButtonColumn',
            'viewButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/view/".$data["id"]',
            'updateButtonUrl'=>'Yii::app()->controller->createUrl("update",$data->primaryKey)',
            'deleteButtonUrl'=>'Yii::app()->controller->createUrl("delete",$data->primaryKey)',
            "htmlOptions" => array(
                'style'=>'width: 60px;'
            )
        )
    )
)); ?> 
If you need to get total items count find by CDbCriteria you need to write:
$model->search()->getTotalItemCount(); 
 
But if you want to customize your data provider with custom limit and offset params then you need
to set 'offset' and 'limit' option to 'CDbCriteria' class as following and need to set pagination to false:

 
$criteria=new CDbCriteria;
$criteria->order = $this->sortString;
$criteria->offset = 5;
$criteria->limit = 10;

return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
    "pagination" => false
));