Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @file
- * Displays children pages as a block
- */
- namespace Drupalchild_pages_displayPluginBlock;
- use DrupalCoreBlockBlockBase;
- use DrupalCoreUrl;
- use DrupalCorePath;
- use DrupalCoreMenu;
- /**
- * Provides a 'Next Previous' block.
- *
- * @Block(
- * id = "child_page_block",
- * admin_label = @Translation("Child Page Block"),
- * category = @Translation("Blocks")
- * )
- */
- class ChildPageBlock extends BlockBase {
- public function build(){
- $menu_tree = Drupal::menuTree();
- $menu_name = 'main';
- // Build the typical default set of menu tree parameters.
- $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
- $expandedParents = $parameters->expandedParents;
- reset($expandedParents);
- $root = current($expandedParents);
- $parameters = new DrupalCoreMenuMenuTreeParameters();
- $parameters->setRoot($root);
- $parameters->setMaxDepth(3);
- $parameters->setMinDepth(1);
- // Load the tree based on this set of parameters.
- $tree = $menu_tree->load($menu_name, $parameters);
- //Set Cache for block
- $cache['max-age'] = 3600;
- $cache['contexts'][] = 'url.path';
- $cache['tags'][] = $root;
- //Get node IDs from menu
- $nids = array();
- foreach($tree as $item){
- $nids[] = $item->link->getUrlObject()->getRouteParameters()['node'];
- }
- //Load nodes & generate content from nodes
- $nodes = (!empty($nids)) ? entity_load_multiple('node', $nids) : array();
- if (!empty($nodes) && is_array($nodes)){
- foreach($nodes as $key=>$val) {
- $nodeContent = array(
- '#prefix' => '<div class="block-child-page-menu">',
- '#suffix' => '</div>'
- );
- $url = Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$key);
- //Get image thumbnail from content & use specified image style
- if(null !== $val->get('field_thumbnail')->entity){
- $imgPath = ($val->get('field_thumbnail')->entity->uri->value);
- $imgCroppedPath = DrupalimageEntityImageStyle::load('basic_page_thumbnail')->buildUrl($imgPath);
- $img = ($imgPath != '') ? '<img src="' . $imgCroppedPath . '" />' : '';
- }else{
- $img = "";
- }
- $nodeContent['#markup'] = '<a href="'.$url.'">' .
- '<h2>' . $val->getTitle() . '</h2>' .
- $img .
- '</a>';
- $content[] = $nodeContent;
- }
- }else{
- //Menu has no nodes
- $content['#markup'] = '';
- }
- //Add cache & css library to block
- $content['#cache'] = $cache;
- $content["#attached"] = array('library' => array('child_pages_display/child_pages_display_css'));
- return $content;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement