5

how can I make a pager with the pager class? I could not find anywhere how to do this with the EntityQuery class. I have a pager(10) that displays the last 10 items. I want to make a pager with numbers like < 1, 2, 3, 4, 5, 6 >.

This is the code I have now:

class NewsArchive extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $news = $query->condition('type', 'news')
      ->condition('status', 1)
      ->sort('created', 'DESC')
      ->pager(10)
      ->execute();

    // LoadMultiple News in $nodes variable
    $nodes = Node::loadMultiple($news);

    $path = base_path();

    // Return $nodes variable with name items to the module.
    return array(
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    );

  }
}

I have read somewhere that this was possible with the following code:

      $build['pager'] = [
        '#type' => 'pager',
      ];

How does this build pager (render) fit into my code? Can someone show me how to start?

2

Add the pager to the build array in which you return the results:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    ],
    'pager' => [
      '#type' => 'pager',
    ],
  ];    

Or extend the theme with a variable #pager if you want to theme this in one place:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
      '#pager' => [
        '#type' => 'pager',
      ],
    ],
  ];    

Then you can print the pager in twig:

{{ pager }}
  • And how would I be able to print this in my twig / check the amount of pages etc.? – Luc - K Jun 14 '17 at 14:29
  • you don't have print this, drupal renders all elements it finds in the render array – 4k4 Jun 14 '17 at 14:35
  • I've added an example for the second option – 4k4 Jun 14 '17 at 14:47
  • Thank you for your respone, very helpful. The styling is done by a form or something I guess? – Luc - K Jun 15 '17 at 9:28
  • no, the pager uses links with a query string, you can style the pager in pager.html.twig – 4k4 Jun 15 '17 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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