GroupMenuBlock.php in Group Menu 8
File
modules/groupmenu_block/src/Plugin/Block/GroupMenuBlock.php
View source
<?php
namespace Drupal\groupmenu_block\Plugin\Block;
use Drupal\group\Entity\GroupContent;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\group\Entity\GroupInterface;
use Drupal\Core\Form\FormStateInterface;
class GroupMenuBlock extends BlockBase {
public function defaultConfiguration() {
return [
'max_depth' => 0,
] + parent::defaultConfiguration();
}
public function blockForm($form, FormStateInterface $form_state) {
$form['max_depth'] = [
'#type' => 'select',
'#title' => $this
->t('Max Depth'),
'#default_value' => $this->configuration['max_depth'],
'#weight' => 1,
'#options' => range(0, 10),
'#description' => $this
->t('Set 0 for no limit.'),
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['max_depth'] = $form_state
->getValue('max_depth');
}
protected function getGroupMenus(GroupInterface $group) {
return \Drupal::service('groupmenu.menu')
->loadUserGroupMenusByGroup('view', $group
->id());
}
public function build() {
$node = $this
->getContextValue('node');
if ($node) {
$group_contents = GroupContent::loadByEntity($node);
$menus = [];
foreach ($group_contents as $group_content) {
$group = $group_content
->getGroup();
$menus = array_merge($menus, $this
->getGroupMenus($group));
}
}
else {
$group = $this
->getContextValue('group');
if ($group) {
$menus = $this
->getGroupMenus($group);
}
else {
return [];
}
}
$build = [];
$parameters = new MenuTreeParameters();
if ($max_depth = $this->configuration['max_depth']) {
$parameters
->setMaxDepth($max_depth);
}
$parameters
->onlyEnabledLinks();
$manipulators = [
[
'callable' => 'menu.default_tree_manipulators:checkAccess',
],
[
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
],
];
foreach ($menus as $menu_name => $menu) {
$tree = \Drupal::menuTree()
->load($menu_name, $parameters);
$tree = \Drupal::menuTree()
->transform($tree, $manipulators);
$build[] = \Drupal::menuTree()
->build($tree);
}
return $build;
}
}