Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Pagination Variables from DataProvider

Tags:

yii

I need certain pagination variables in my controller action.

such as:

1.Current Page Number

2.Current Page offset

3.total records displayed

i.e. 31 to 40 of 2005 records displayed

I tried the following:

$dataProvider = NodesTerms::getNodesDataFromTerms($nodeId) ;     
  $pagination = $dataProvider->getPagination();
  var_dump($pagination->getPageCount());
  //var_dump($pagination->currentPage);

I can get the Pagination Object, but zero (0) in $pagination->currentPage or $pagination->offset etc....

I need this information to dynamically generate meta page title and description on actions with page listings such as pagetitle: page 3 of 10 for American Recipes...

Appreciate any help with this.

like image 502
Raheel Dharolia Avatar asked Nov 06 '12 15:11

Raheel Dharolia


1 Answers

Try setting the itemCount explicitly in your dataProvider:

'pagination'=>array(
    'pageSize'=>10,
    'itemCount'=>$count
)

Or use a new CPagination object:

$pagination = new CPagination($count);

$dataProvider = new CSqlDataProvider($sql, array(
    // ... other config
    'pagination' => $pagination
));

How this works:

The pagination's itemCount is set during creation of the data-provider and again in CSqlDataProvider's fetchData function:

    $pagination->setItemCount($this->getTotalItemCount());

During creation of data-provider only the values passed to the pagination property are used, and if we don't pass itemCount value, then the default of 0 is used.
So if we want to access offset or pageCount or currentPage or itemCount before the call to fetchData we have to set the itemCount explicitly.

However if we want those values after the call to fetchData then the values are already correctly populated due to the call to setItemCount within fetchData.

An example for clarity (without passing itemCount during data-provider creation):

$dataProvider = NodesTerms::getNodesDataFromTerms($nodeId);     
$pagination = $dataProvider->getPagination();
var_dump($pagination->getPageCount()); // this will be zero

$data=$dataProvider->getData(); // getData calls fetchData()

var_dump($pagination->getPageCount()); // now this will be correct value 
like image 134
bool.dev Avatar answered Oct 22 '22 19:10

bool.dev