Guest User

Untitled

a guest
Jul 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. <?php
  2.  
  3. use Drupal\views\Views;
  4.  
  5. // Optional, if using filter values passed via URL (see example below).
  6. use Drupal\Component\Utility\Html;
  7.  
  8. /**
  9. * Preprocesses variables for node--NODE_TYPE.html.twig.
  10. *
  11. * Replace 'mytheme' with the name of your theme, and NODE_TYPE and VIEW_NAME
  12. * with actual machine names.
  13. */
  14. function mytheme_preprocess_node__NODE_TYPE(&$variables) {
  15.  
  16. $node = $variables['node'];
  17.  
  18. // Execute the view that provides the context.
  19. $view = \Drupal\views\Views::getView('VIEW_NAME');
  20.  
  21. // Optionally set a contextual filter value passed in via the URL;
  22. // e.g. path-to-node?vid=456. You will need to add the parameter to the pager
  23. // URLs in your Twig template.
  24. $variables['arg'] = Html::escape(\Drupal::request()->query->get('vid'));
  25. $view->setArguments([$variables['arg']]);
  26.  
  27. $view->execute();
  28.  
  29. // Iterate through the results to find the results index for previous,
  30. // current, and next nodes.
  31. $match = FALSE;
  32. foreach ($view->result as $k => $row) {
  33. // Break out of iterator when we find the next row.
  34. if ($match !== FALSE) {
  35. $next = $k;
  36. break;
  37. }
  38. // This result matches our currently loaded node.
  39. if ($row->nid == $node->id()) {
  40. $match = $k;
  41. }
  42. // As long as we haven't reached a match, let's keep updating $previous.
  43. if ($match === FALSE) {
  44. $previous = $k;
  45. }
  46. }
  47.  
  48. // If a match is found, set up our template variables.
  49. if ($match !== FALSE) {
  50. $variables['node_view_pager'] = [];
  51. $variables['node_view_pager']['num_results'] = count($view->result);
  52. $variables['node_view_pager']['index'] = $match + 1;
  53. $controller = \Drupal::entityManager()->getStorage('node');
  54. if (isset($previous)) {
  55. $variables['node_view_pager']['previous'] = $controller->load($view->result[$previous]->nid);
  56. }
  57. if (isset($next)) {
  58. $variables['node_view_pager']['next'] = $controller->load($view->result[$next]->nid);
  59. }
  60. }
  61. }
Add Comment
Please, Sign In to add comment