Skip to content

Instantly share code, notes, and snippets.

@opi
Created September 28, 2021 11:41
Show Gist options
  • Save opi/6f5c0c750447702092c1ed6e56e6c7f8 to your computer and use it in GitHub Desktop.
Save opi/6f5c0c750447702092c1ed6e56e6c7f8 to your computer and use it in GitHub Desktop.
Drupal Views pager as block
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\views\Views;
/**
* Provides a 'Views pager' block.
*
* @Block(
* id = "views_pager",
* admin_label = @Translation("Agenda Pager"),
* )
*/
class MyModuleViewsPager extends BlockBase implements ContainerFactoryPluginInterface {
/**
* Drupal\Core\Routing\RouteMatchInterface definition.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = new static($configuration, $plugin_id, $plugin_definition);
$instance->routeMatch = $container->get('current_route_match');
return $instance;
}
/**
* {@inheritdoc}
*/
public function build() {
// Current page is a view ?
$view_id = $this->routeMatch->getParameter('view_id');
if (!empty($view_id)) {
// Get current route
$route = $this->routeMatch->getRouteObject();
// Get view id and display id from route.
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');
if (!empty($view_id) && !empty($display_id)) {
// Get the view by id.
$view = Views::getView($view_id);
if ($view) {
// Set display id.
$view->setDisplay($display_id);
// Handle arguments
// $arg_0 = $this->routeMatch->getParameter('arg_0');
// $view->setArguments(['arg_0' => $arg_0]);
$arguments = $this->routeMatch->getParameters()->all();
unset($arguments['view_id']);
unset($arguments['display_id']);
$view->setArguments($arguments);
// Execute view
$view->execute();
// Render pager
$pager = $view->getPager();
$input = $view->getExposedInput();
return [
'pager' => $pager->render($input)
];
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment