To add Pager in custom table view, append the following code (line 1 & 2) in your module.

  $query = db_select('mymodule', 'mym');
  $query->fields('mym');
  $query = $query->extend('PagerDefault')->limit(5); // line1
  $result = $query->execute();
..

$output = theme('table',..
$output .= theme('pager'); // line2
return $output;

Comments

imranweb’s picture

You are asking on telling others?

vickey’s picture

I sharing(telling) this info to all who new to drupal 7

Anonymous’s picture

Thk for sharing, where i search for pager one array with no db_select (direct multiarray)?
Bye !

alexmoreno’s picture

lgrtm, you are maybe interested on this:

/**
 * Page callback for some paged data.
 */
function mysite_some_paged_data() {
  $output = NULL;
  $rows = mysite_generate_a_big_array();
  if (!empty($rows)) {
    $limit = 20;
    $page = pager_default_initialize(count($rows), $limit, 0);
    $offset = $limit * $page;
    $output = array(
      array(
        '#theme' => 'item_list',
        '#items' => array_slice($rows, $offset, $limit),
      ),
      array(
        '#theme' => 'pager',
      ),
    );
  }
}

via: http://chacadwa.com/blog/2013/03/12/drupal-7-display-array-contents-pager

rakesh.gectcr’s picture

<?php
$per_page = 10;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));
?>

---
Kind regards,

Thank you,
Rakesh James

K99’s picture

rakesh.gectcr That was very helpful, but i can't seem to limit the number of records displayed.

Jaypan’s picture

What does your code look like?

K99’s picture

I was able to go about the problem. I could Limit my pager to any amount by just changing the value in "limit(value)" I set mine to 50. And the header is sticky too. Thanks yall! Here is the code sorry its a bit messy.


<?php

function report() {
	
 $header = array(
'sn' => array('data' => t('S.No'), 'field' => 'registration2.ukey'),
'ukey' => array('data' => t('Reg.No'), 'field' => 'registration2.ukey'),
'name' => array('data' => t('Name'), 'field' => 'registration2.name'),
'gender' => array('data' => t('Gender'), 'field' => 'registration2.gender'),
'date_birth' => array('data' => t('Date of Birth'), 'field' => 'registration2.date_birth'),
'reg_date' => array('data' => t('Registered Date'), 'field' => 'registration2.reg_date'),
'anc' => array('data' => t('Ante Natal Care'), 'field' => 'registration2.anc'),
'edit' =>array('data' => t('View'), 'colspan' => 2)
);

$query = db_select('registration2');
$count_query = clone $query;
$count_query->addExpression('COUNT(registration2.ukey)');
$query = $query->extend('PagerDefault')->extend('TableSort');
$query
->fields('registration2', array( 'ukey', 'lname','fname', 'mname', 'gender', 'date_birth', 'reg_date', 'anc'))
// where Limit value to 50
->limit(50)
->orderByHeader($header)
->setCountQuery($count_query);
$result = $query->execute();

$rows = array();
$sn=$ukey;
foreach ($result as $folk) {

$sn =  $folk->ukey;
$ukey =  $folk->ukey;
 $uk =  $folk->ukey;
 $uk = '0000'.$folk->ukey;
 $anc =$folk->anc;

 if ($anc==1){$kgg='Yes';}
 else {$kgg='No';}

 $gender = $folk->gender;
 $gen = $folk->gender;

 if ($gender==1) {$gen='Male';}
 else {$gen='Female';}

$rows[$folk->ukey] = array(
'sn' =>  $sn,
'uk' =>  $uk,
'name' => ($folk->fname. '  ' .$folk->mname.'  '.$folk->lname),
'gen' => $gen,
'date_birth' => ($folk->date_birth),
'reg_date' => ($folk->reg_date),
'kgg' =>  $kgg,
'edit' => l('Edit', 'view_print_search/',array("query"=>array("ukey" => $folk->ukey,"ukey" => $folk->ukey))),
);

}

$vars['header'] = $header;
$vars['empty'] = 'Empty List - No Entries';
$vars['rows'] = $rows;
$render_array['table'] = array(
'#theme' => 'table',
'#rows' => $rows,
'#empty' => 'Empty List - No Entries',
'#header' => $header,
);

$render_array['pager'] = array(
'#theme' => 'pager',
);

return $render_array;
}

Danny Ndiaye’s picture

Great! Thanks Rakesh.

Sridar’s picture

Thanks Rakesh for the simple and understandable solution.

mahianu’s picture

Hi,

how to add id to this pager so that it is applied only for this part of the code.

thanks

Sift’s picture

Hi mahianu,

if your goal is to add an HTML id to the pager, you could take advantage of the variable 'element', designed to be unique and distinguish between several pagers in the same page, to override the theme function and add wrap the element with a container with an unique id.

You could do it in the template.php of your theme:

/**
 * Implements theme_pager.
 */
function <theme_name>_pager($variables) {

  if (isset($variables['element']) && is_int($variables['element'])) {
    $html_id = drupal_html_id('pager-' . $variables['element']);
    $prefix = '<div id="' . $html_id . '">';
    $suffix = '</div>';

    return $prefix . theme_pager($variables) . $suffix;
  }

  return theme_pager($variables);
}

Using the pager theme as, for example:

// Attach the pager.
  $page['pager'] = array(
    '#theme' => 'pager',
    '#element' => 0,
    '#quantity' => ...,
    ...
  );

will create a container like:

<div id="pager-0">
  <h2 class="element-invisible">Pages</h2>
  <div class="item-list">
    <ul class="pager">...
mohd.shadab’s picture

I applied above method in views tpl. When i click on pager number, My table data does empty. Any solution please.?

aniket.mohite88’s picture

Thanks rakesh,
This is very useful to create pagers for rows available in array. Very helpful.

arruk’s picture

Drupal docs says to avoid calling theme() directly:

Avoid calling this function directly. It is preferable to replace direct calls to the theme() function with calls to drupal_render() by passing a render array with a #theme key to drupal_render(), which in turn calls theme().

steven.wichers’s picture

That does not apply to theme implementations that are overriding the theme you are calling. If you follow that guideline you will wind up with a recursion where your theme function calls itself.

function MYTHEME_pager($var) {
  return render(array('#theme' => 'pager'));
}

Drupal will translate the render array into theme('pager') which then goes through the normal theming process and will call MYTHEME_pager again. Calling theme_pager() directly in the theme implementation bypasses that process within Drupal.

The downside is if anything else is modifying pagers it may not have a chance to act.

Rohit kumar jha’s picture

rakesh.gectcr It works for me.Thanks

SivaprasadC’s picture

zaurav’s picture

Thanks @rakesh.getctcr! If someone need tablesort on it you could use db_select and do it like so:

function table_sort_and_pagination() {

//Initialize header with items you need
  $header = array(
    array('data' => 'User',        'field' => 'uid',               'sort' => 'ASC'),
    array('data' => 'Status',        'field' => 'status', 'sort' => 'ASC'),
    array('data' => 'Date',     'field' => 'time_stamp',       'sort' => 'ASC'),
    array('data' => 'Description', 'field' => 'message'),
  );
  $data = array();
//use db_select cuz it allows for extenders!
  $select = db_select('lm_user', 'lm')
    // the following two are the out of the box extenders Drupal provides. 
    // PagerDefault paginates the results, TableSort puts it in a sortable table (click on header to sort)
    ->extend('PagerDefault')
    ->extend('TableSort');


  $select
    ->fields('lm', array('uid','status','time_stamp','message'))
    // How many items you want per page?
    ->limit(25)
    // This method is provided by TableSort class and is important otherwise your table will not sort.
    ->orderByHeader($header);

 
  $result = $select->execute();

  $rows = array();
  foreach($result as $row) {
    // Here you iterate over your row items and do any sort of processing like converting timestamp or loading user name (IF YOU NEED). Otherwise just an array of data straight from the db_select should be fine.
    $rows[] = array(user_load($row->uid)->name, $row->status, date('m-d-Y',$row->time_stamp), $row->message);
  }

  // This is how to output your data as a table.
  $output = theme('table', array('header' => $header,
    'rows' => $rows ));

  // add the pager
  $output .= theme('pager');

  return $output;
}
sgourebi’s picture

//an exemple

function collection_list(){
// définir le header du tableau
$header = array(
array('data' => t('Titre'), 'field' => 'title', 'sort' => 'ASC'),
);

// recupération des collection
$collections = db_select('node', 'n')
->fields('n')
->condition('n.type', 'collection', '=')
->execute()
->fetchAll();
 
// definir les lignes
foreach($collections as $collection){
$rows[] = array(
'<a href="language/translate/collection/'.$collection->nid.'">'.$collection->title.'</a>'
);
}
// nombre par page
$per_page = 10;
$current_page = pager_default_initialize(count($rows), $per_page);
$split_list = array_chunk($rows, $per_page, TRUE);

// faire le rendu
$output = theme('table', array(
'header' => $header,
'rows' => $split_list[$current_page]
));
 
// ajout de la pagination
$output .= theme('pager');
return $output;

}

joseabrahamg’s picture

Excuse my bad English, i'm afraid that 

array('quantity',count($rows))

Is not correct, it would be like this:

array('quantity' => count($rows))

Even better:

$output .= theme('pager', ['quantity' => count($rows)]);
parthapratimg’s picture

Thanks @rakesh.gectcr, its save my time.

murnikov’s picture

    $count_query = db_select('v_client_bookings')
        ->condition('account_id', $account_id);
    $count_query->addExpression('COUNT(training_id)');
    $query = db_select('v_client_bookings', 'b')
        ->fields('b', [
            'training_id', 'visit_id', 'account_id',
            'start', 'title_en', 'title_et', 'title_ru',
            'room_en', 'room_ru', 'room_et',
            'price', 'slots', 'no_show', 'comments',
            'currency', 'customer_name',
        ])
        ->condition('account_id', $account_id)
        ->orderBy('timestamp', 'DESC')
        ->extend('PagerDefault')
        ->limit(10)
        ->setCountQuery($count_query);      
        $bookings = $query->execute();

execute() method triggers error "Call to a member function execute() on null"

Removing the setCountQuery() method call alleviates the immediate problem but I"m afraid won't be able to render pager

Any ideas what am I doing wrong ?

steven.wichers’s picture

setCountQuery does not return anything. You are assigning null to $query. You must create your query and then call setCountQuery separately.

murnikov’s picture

On what object am I supposed to envoke setCountQuery then ?