You are here

class EntitySubmenuBlock in Entity Submenu Block 8

Same name in this branch
  1. 8 src/Plugin/Derivative/EntitySubmenuBlock.php \Drupal\entity_submenu_block\Plugin\Derivative\EntitySubmenuBlock
  2. 8 src/Plugin/Block/EntitySubmenuBlock.php \Drupal\entity_submenu_block\Plugin\Block\EntitySubmenuBlock

Provides an Entity Submenu Block.

Plugin annotation


@Block(
  id = "entity_submenu_block",
  admin_label = @Translation("Entity Submenu Block"),
  category = @Translation("Menus"),
  deriver = "Drupal\entity_submenu_block\Plugin\Derivative\EntitySubmenuBlock"
)

Hierarchy

Expanded class hierarchy of EntitySubmenuBlock

File

src/Plugin/Block/EntitySubmenuBlock.php, line 24

Namespace

Drupal\entity_submenu_block\Plugin\Block
View source
class EntitySubmenuBlock extends SystemMenuBlock {

  /**
   * The active menu trail service.
   *
   * @var \Drupal\Core\Menu\MenuActiveTrailInterface
   */
  protected $menuActiveTrail;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  protected $entityDisplayRepository;

  /**
   * All entity types.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface[]
   */
  protected $entityTypes;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $static = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $static
      ->setMenuActiveTrail($container
      ->get('menu.active_trail'));
    $static
      ->setEntityTypeManager($container
      ->get('entity_type.manager'));
    $static
      ->setEntityDisplayRepository($container
      ->get('entity_display.repository'));
    $static
      ->setEntityTypes($container
      ->get('entity_type.manager')
      ->getDefinitions());
    return $static;
  }
  public function setMenuActiveTrail(MenuActiveTrailInterface $menuActiveTrail) {
    $this->menuActiveTrail = $menuActiveTrail;
  }
  public function setEntityTypeManager(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }
  public function setEntityDisplayRepository(EntityDisplayRepositoryInterface $entityDisplayRepository) {
    $this->entityDisplayRepository = $entityDisplayRepository;
  }
  public function setEntityTypes(array $entityTypes) {
    $this->entityTypes = $entityTypes;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    // We don't need the menu levels options from the parent.
    unset($form['menu_levels']);
    $config = $this
      ->getConfiguration();

    // Display non-entities.
    $form['display_non_entities'] = [
      '#title' => $this
        ->t('Display non-entities'),
      '#type' => 'checkbox',
      '#default_value' => $this
        ->getConfigurationValue($config, 'display_non_entities'),
    ];

    // Only display entities with content in current language.
    $form['only_current_language'] = [
      '#type' => 'checkbox',
      '#title' => t('Only display entities with content in current language'),
      '#default_value' => $this
        ->getConfigurationValue($config, 'only_current_language'),
    ];

    // View modes fieldgroup.
    $form['view_modes'] = [
      '#title' => $this
        ->t('View modes'),
      '#description' => $this
        ->t('View modes to be used when submenu items are displayed as content entities'),
      '#type' => 'fieldgroup',
      '#process' => [
        [
          get_class(),
          'processFieldSets',
        ],
      ],
    ];

    // A select list of view modes for each entity type.
    foreach ($this
      ->getEntityTypes() as $entity_type) {
      $field = 'view_mode_' . $entity_type;
      $view_modes = $this->entityDisplayRepository
        ->getViewModeOptions($entity_type);
      $form['view_modes'][$field] = [
        '#title' => $this->entityTypeManager
          ->getDefinition($entity_type)
          ->getLabel(),
        '#type' => 'select',
        '#options' => $view_modes,
        '#default_value' => $this
          ->getConfigurationValue($config, $field, array_keys($view_modes)),
      ];
    }
    return $form;
  }

  /**
   * Form API callback: Processes the elements in field sets.
   *
   * Adjusts the #parents of field sets to save its children at the top level.
   */
  public static function processFieldSets(&$element, FormStateInterface $form_state, &$complete_form) {
    array_pop($element['#parents']);
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    foreach ([
      'display_non_entities',
      'only_current_language',
    ] as $field) {
      $this
        ->setConfigurationValue($field, $form_state
        ->getValue($field));
    }
    foreach ($this
      ->getEntityTypes() as $entity_type) {
      $field = 'view_mode_' . $entity_type;
      $value = $form_state
        ->getValue($field);
      $this
        ->setConfigurationValue($field, $value);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [
      '#theme' => 'entity_submenu',
      '#menu_name' => NULL,
      '#menu_items' => [],
    ];

    // Get the menu name.
    $menu_name = $this
      ->getDerivativeId();

    // Return empty menu items array if the active trail is not in this menu.
    if (empty($this->menuActiveTrail
      ->getActiveLink($menu_name))) {
      return $build;
    }

    // The menu name is only set if the active trail is in this menu.
    $build['#menu_name'] = $menu_name;
    $parameters = $this->menuTree
      ->getCurrentRouteMenuTreeParameters($menu_name);

    // Get current level from end of active trail.
    $level = count($parameters->activeTrail);
    $parameters
      ->setMinDepth($level);

    // We only want the current level.
    $parameters
      ->setMaxDepth($level);

    // We only want enabled links.
    $parameters
      ->onlyEnabledLinks();
    $tree = $this->menuTree
      ->load($menu_name, $parameters);
    $manipulators = [
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
    ];
    $tree = $this->menuTree
      ->transform($tree, $manipulators);
    $config = $this
      ->getConfiguration();
    $language = \Drupal::languageManager()
      ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
      ->getId();
    foreach ($tree as $element) {

      // Skip inaccessible links.
      if ($element->link instanceof InaccessibleMenuLink) {
        continue;
      }
      $url = $element->link
        ->getUrlObject();

      // Only try to get route parameters from routed links.
      if ($url
        ->isRouted()) {
        $routeParams = $url
          ->getRouteParameters();
        reset($routeParams);
        $entity_type = key($routeParams);
        if (in_array($entity_type, $this
          ->getEntityTypes())) {

          // The link is an entity link.
          $entity = $this->entityTypeManager
            ->getStorage($entity_type)
            ->load($routeParams[$entity_type]);
          if ($this
            ->getConfigurationValue($config, 'only_current_language') == 1) {
            $languages = $entity
              ->getTranslationLanguages();
            if (!array_key_exists($language, $languages)) {

              // Skip this entity as content is not translated in current language.
              continue;
            }
          }

          // Get render array and continue to next menu item.
          $build['#menu_items'][] = $this->entityTypeManager
            ->getViewBuilder($entity_type)
            ->view($entity, $config['view_mode_' . $entity_type]);
          continue;
        }
      }

      // The link is a routed non-entity link or an external link.
      // If the configuration option is set, create a render array.
      if ($this
        ->getConfigurationValue($config, 'display_non_entities') == 1) {
        $build['#menu_items'][] = [
          '#theme' => 'entity_submenu_item',
          '#url' => $url,
          '#title' => $element->link
            ->getTitle(),
        ];
      }
    }
    return $build;
  }

  /**
   * Returns a configuration value for a specified field.
   *
   * @param array $config
   *   Array containing the configuration.
   * @param string $field
   *   Name of the field to get a value for.
   * @param array $valid
   *   Optional array containing valid values for the field.
   *
   * @return value
   *   Value for the field or NULL.
   */
  protected function getConfigurationValue(array $config, $field, array $valid = NULL) {
    $value = NULL;
    if (isset($config[$field]) && !empty($config[$field])) {
      if (is_array($valid)) {
        if (in_array($config[$field], $valid)) {
          $value = $config[$field];
        }
      }
      else {
        $value = $config[$field];
      }
    }
    return $value;
  }

  /**
   * Returns a list of valid entity types.
   *
   * @return array
   *   Valid entity type names.
   */
  protected function getEntityTypes() {
    $entity_types = [
      'node',
    ];
    foreach ($this->entityTypes as $entity_type => $definition) {
      if ($entity_type != 'node' && $this
        ->isValidEntity($entity_type)) {
        $entity_types[] = $entity_type;
      }
    }
    return $entity_types;
  }

  /**
   * Filters entities based on their view builder handlers.
   *
   * @param string $entity_type
   *   The entity type of the entity that needs to be validated.
   *
   * @return bool
   *   TRUE if the entity has the correct view builder handler, FALSE if the
   *   entity doesn't have the correct view builder handler.
   */
  protected function isValidEntity($entity_type) {
    return $this->entityTypes[$entity_type]
      ->get('field_ui_base_route') && $this->entityTypes[$entity_type]
      ->hasViewBuilderClass();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. 2
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntitySubmenuBlock::$entityDisplayRepository protected property The entity display repository.
EntitySubmenuBlock::$entityTypeManager protected property The entity type manager.
EntitySubmenuBlock::$entityTypes protected property All entity types.
EntitySubmenuBlock::$menuActiveTrail protected property The active menu trail service. Overrides SystemMenuBlock::$menuActiveTrail
EntitySubmenuBlock::blockForm public function Overrides SystemMenuBlock::blockForm
EntitySubmenuBlock::blockSubmit public function Overrides SystemMenuBlock::blockSubmit
EntitySubmenuBlock::build public function Builds and returns the renderable array for this block plugin. Overrides SystemMenuBlock::build
EntitySubmenuBlock::create public static function Creates an instance of the plugin. Overrides SystemMenuBlock::create
EntitySubmenuBlock::getConfigurationValue protected function Returns a configuration value for a specified field.
EntitySubmenuBlock::getEntityTypes protected function Returns a list of valid entity types.
EntitySubmenuBlock::isValidEntity protected function Filters entities based on their view builder handlers.
EntitySubmenuBlock::processFieldSets public static function Form API callback: Processes the elements in field sets.
EntitySubmenuBlock::setEntityDisplayRepository public function
EntitySubmenuBlock::setEntityTypeManager public function
EntitySubmenuBlock::setEntityTypes public function
EntitySubmenuBlock::setMenuActiveTrail public function
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SystemMenuBlock::$menuTree protected property The menu link tree service.
SystemMenuBlock::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
SystemMenuBlock::getCacheContexts public function The cache contexts associated with this object. Overrides ContextAwarePluginBase::getCacheContexts
SystemMenuBlock::getCacheTags public function The cache tags associated with this object. Overrides ContextAwarePluginBase::getCacheTags
SystemMenuBlock::processMenuLevelParents public static function Form API callback: Processes the menu_levels field element.
SystemMenuBlock::__construct public function Constructs a new SystemMenuBlock. Overrides BlockPluginTrait::__construct
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2