Tuesday, January 15, 2019

Show previous chapter, next chapter navigation in book page of Drupal 8.

Q: I want to show a navigation to previous chapter & next chapter in my book detail page(node view). I'll explain the scenario: I have a parent book and multiple child pages, each may have children up-to level n. I'm showing the level 1(depth 2) pages in a single view(details page) and the children in same page. Here comes the navigation part. I want to show a navigation to previous and next chapters in the Book details page.

A: After creation of the Book page details page, create a view as per the below pictures

1.Create a View-Give name and select the content type. Check 'Create a Block'.

2. As per the scenario I want to see Level 2 book pages(siblings of current page), so I set Depth is equal to 2 under Filter criteria. Sort criteria set us Depth's Ascending order.
3. Created a contextual filter: Node ID and set its default value from the URL(as we are viewing the node view page)
4. Under more we have to check the exclude option so that the result will exclude the current book page.

5.Save the view. See I created two blocks , one for previous link and one for next link. 
By visiting structure > Block Layout you are able to place the newly created blocks.

 6. Now we have to create a module to apply some query conditions to the view. Simply create a module and paste the below code in your module's .module file and enable it.

<?php
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
/**
 * To get the next and previous chapters
 *
 * @param ViewExecutable $view
 * @param QueryPluginBase $query
 * @return void
 */
function chapter_navigation_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {   
  
  $node = \Drupal::routeMatch()->getParameter('node');
  
  if ($view->id() == 'chapter_navigation' && $node) {
    $operator = $view->getDisplay()->display['id'] == 'next_chapter' ? '>=' : '<=';
    foreach ($query->where as &$condition_group) {
      array_push($condition_group['conditions'], [
        'field' => 'book.weight '.$operator.' ' . $node->book['weight'],
        'value' => [],
        'operator' => 'formula',

      ]);

    }   
 
  }

}

No comments:

Post a Comment