You are here

class PagerExamplePage in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/pager_example/src/Controller/PagerExamplePage.php \Drupal\pager_example\Controller\PagerExamplePage

Controller for pager_example.page route.

This is an example describing how a module can implement a pager in order to reduce the number of output rows to the screen and allow a user to scroll through multiple screens of output.

Hierarchy

Expanded class hierarchy of PagerExamplePage

File

pager_example/src/Controller/PagerExamplePage.php, line 18

Namespace

Drupal\pager_example\Controller
View source
class PagerExamplePage extends ControllerBase {

  /**
   * Entity storage for node entities.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $nodeStorage;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * PagerExamplePage constructor.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
   *   Entity storage for node entities.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   */
  public function __construct(EntityStorageInterface $node_storage, AccountInterface $current_user) {
    $this->nodeStorage = $node_storage;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $controller = new static($container
      ->get('entity_type.manager')
      ->getStorage('node'), $container
      ->get('current_user'));
    $controller
      ->setStringTranslation($container
      ->get('string_translation'));
    return $controller;
  }

  /**
   * Content callback for the pager_example.page route.
   */
  public function getContent() {

    // First we'll tell the user what's going on. This content can be found
    // in the twig template file: templates/description.html.twig. It will be
    // inserted by the theming function pager_example_description().
    $build = [
      'description' => [
        '#theme' => 'pager_example_description',
        '#description' => $this
          ->t('description'),
        '#attributes' => [],
      ],
    ];

    // Ensure that this page's cache is invalidated when nodes have been
    // published, unpublished, added or deleted; and when user permissions
    // change.
    $build['#cache']['tags'][] = 'node_list';
    $build['#cache']['contexts'][] = 'user.permissions';

    // Now we want to get our tabular data. We select nodes from node storage
    // limited by 2 per page and sort by nid DESC because we want to show newest
    // node first. Additionally, we check that the user has permission to
    // view the node.
    $query = $this->nodeStorage
      ->getQuery()
      ->sort('nid', 'DESC')
      ->addTag('node_access')
      ->pager(2);

    // The node_access tag does not trigger a check on whether a user has the
    // ability to view unpublished content. The 'bypass node access' permission
    // is really more than we need. But, there is no separate permission for
    // viewing unpublished content. There is a permission to 'view own
    // unpublished content', but we don't have a good way of using that in this
    // query. So, unfortunately this query will incorrectly eliminate even those
    // unpublished nodes that the user may, in fact, be allowed to view.
    if (!$this->currentUser
      ->hasPermission('bypass node access')) {
      $query
        ->condition('status', 1);
    }
    $entity_ids = $query
      ->execute();
    $nodes = $this->nodeStorage
      ->loadMultiple($entity_ids);

    // We are going to output the results in a table so we set up the rows.
    $rows = [];
    foreach ($nodes as $node) {

      // There are certain things (besides unpublished nodes) that the
      // node_access tag won't prevent from being seen. The only way to get at
      // those is by explicitly checking for (view) access on a node-by-node
      // basis. In order to prevent the pager from looking strange, we will
      // "mask" these nodes that should not be accessible. If we don't do this
      // masking, it's possible that we'd have lots of pages that don't show any
      // content.
      $rows[] = [
        'nid' => $node
          ->access('view') ? $node
          ->id() : $this
          ->t('XXXXXX'),
        'title' => $node
          ->access('view') ? $node
          ->getTitle() : $this
          ->t('Redacted'),
      ];
    }

    // Build a render array which will be themed as a table with a pager.
    $build['pager_example'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('NID'),
        $this
          ->t('Title'),
      ],
      '#rows' => $rows,
      '#empty' => $this
        ->t('There are no nodes to display. Please <a href=":url">create a node</a>.', [
        ':url' => Url::fromRoute('node.add', [
          'node_type' => 'page',
        ])
          ->toString(),
      ]),
    ];

    // Add our pager element so the user can choose which pagination to see.
    // This will add a '?page=1' fragment to the links to subsequent pages.
    $build['pager'] = [
      '#type' => 'pager',
      '#weight' => 10,
    ];
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PagerExamplePage::$currentUser protected property The current user. Overrides ControllerBase::$currentUser
PagerExamplePage::$nodeStorage protected property Entity storage for node entities.
PagerExamplePage::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
PagerExamplePage::getContent public function Content callback for the pager_example.page route.
PagerExamplePage::__construct public function PagerExamplePage constructor.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.