0

In a custom module I have a block defined and the function that builds the block returns a render array. In that render array I am looking to create a pager for my content since it is a listing of items.

If I run pager_default_initialize during my query building like so this automatically adds a pager to the top of the block.

$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_default_initialize($total, $per);

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

I want to have more control over the pager, like adding it to the bottom of the block. If I remove the pager_default_initialize from the query building code like so, I can stop the pager from automatically being added.

$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

So, the question is, how do I add the pager to my render array so it renders the pager at the bottom of the block?

My render array currently looks like this:

$content['results'] = array(
  '#type'       => 'container',
  '#attributes' => array(
    'class' => 'results',
  ),
);

if ($data->rowCount()) {
  foreach ($data as $record) {
    $content['results'][] = array(
      '#theme' => 'CUSTOM_NODE_THEME',
      '#node'   => node_load($record->nid),
    );
  }
  if ($per > 0) {
    $content['results']['pager'] = array(
      '#theme' => 'pager',
    );
  }
}

The theme_pager() is not being run when the block is rendered.

Any help would be awesome!

1 Answer 1

0

Here is the solution. I knew as soon as I asked the question I would find the answer!

First off, the query building code must not run pager_default_initialize, like so:

$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

The pager render array should be created like so:

$content['results']['pager'] = array(
  '#pre_render' => array('CUSTOM_PRE_RENDER'),
  '#theme' => 'pager',
  '#variables' => array(
    'total' => $total,
    'per' => $per,
  ),
);

And then run pager_default_initialize in the custom pre render function:

function custom_pre_render_intialize_pager($_element) {
  pager_default_initialize($_element['#variables']['total'], $_element['#variables']['per']);

  return $_element;
}

This code will only work to add a single pager to the block and may not work if there is more then one pager on the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.