You are here

class NiceMenusBlock in Nice Menus 8

Provides a 'Nice menus' block.

Plugin annotation


@Block(
  id = "nice_menus_block",
  admin_label = @Translation("Nice menus"),
  category = @Translation("Menus")
)

Hierarchy

Expanded class hierarchy of NiceMenusBlock

File

src/Plugin/Block/NiceMenusBlock.php, line 20

Namespace

Drupal\nice_menus\Plugin\Block
View source
class NiceMenusBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $menuSelector;

  /**
   * NiceMenusBlock constructor.
   *
   * @param array  $configuration
   * @param string $plugin_id
   * @param mixed  $plugin_definition
   * @param        $menuSelector
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, $menuSelector) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->menuSelector = $menuSelector;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('menu.parent_form_selector'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'nice_menus_menu' => 'admin:',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this
      ->getConfiguration();
    $form['nice_menus_name'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Menu name'),
      '#default_value' => isset($config['nice_menus_name']) ? $config['nice_menus_name'] : '',
    );
    $form['nice_menus_menu'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Menu parent'),
      '#description' => $this
        ->t('The menu parent from which to show a Nice menu.'),
      '#default_value' => isset($config['nice_menus_menu']) ? $config['nice_menus_menu'] : 'navigation:0',
      '#options' => $this->menuSelector
        ->getParentSelectOptions(),
    );
    $form['nice_menus_depth'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Menu depth'),
      '#description' => $this
        ->t('The depth of the menu, i.e. the number of child levels starting with the parent selected above. Leave set to -1 to display all children and use 0 to display no children.'),
      '#default_value' => isset($config['nice_menus_depth']) ? $config['nice_menus_depth'] : -1,
      '#options' => array_combine(range(-1, 5), range(-1, 5)),
    );
    $form['nice_menus_type'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Menu style'),
      '#description' => $this
        ->t('right: menu items are listed on top of each other and expand to the right') . '<br />' . $this
        ->t('left: menu items are listed on top of each other and expand to the left') . '<br />' . $this
        ->t('down: menu items are listed side by side and expand down'),
      '#default_value' => isset($config['nice_menus_type']) ? $config['nice_menus_type'] : 'right',
      '#options' => array_combine(array(
        'right',
        'left',
        'down',
      ), array(
        'right',
        'left',
        'down',
      )),
    );
    $form['nice_menus_respect_expand'] = array(
      '#type' => 'select',
      '#title' => $this
        ->t('Respect "Show as expanded" option'),
      '#description' => $this
        ->t('Menu items have a "Show as expanded" option, which is disabled by default. Since menu items do NOT have this option checked by default, you should choose Yes here once you have configured the menu items that you DO want to expand.'),
      '#options' => array(
        0 => $this
          ->t('No'),
        1 => $this
          ->t('Yes'),
      ),
      '#default_value' => isset($config['nice_menus_respect_expand']) ? $config['nice_menus_respect_expand'] : 0,
    );
    return $form;
  }

  /**
   * @param array                                $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this
      ->setConfiguration([
      'label' => $form_state
        ->getValue('label'),
      'label_display' => $form_state
        ->getValue('label_display'),
      'nice_menus_name' => $form_state
        ->getValue('nice_menus_name'),
      'nice_menus_menu' => $form_state
        ->getValue('nice_menus_menu'),
      'nice_menus_depth' => $form_state
        ->getValue('nice_menus_depth'),
      'nice_menus_type' => $form_state
        ->getValue('nice_menus_type'),
      'nice_menus_respect_expand' => $form_state
        ->getValue('nice_menus_respect_expand'),
    ]);
  }

  /**
   * // add 'menuparent' class.
   *
   * @param $items
   *
   * @return mixed
   */
  public function _build_sub_menu_menuparent($items) {
    foreach ($items as $k => &$item) {
      if ($item['below']) {
        $item['attributes']
          ->addClass('menuparent');
        $item['below'] = $this
          ->_build_sub_menu_menuparent($item['below']);
      }
    }
    return $items;
  }

  /**
   * add class to nice menus.
   *
   * @param $tree
   * @param $block_config
   *
   * @return mixed
   */
  public function _build_menu_style($tree, $block_config) {

    // add default class.
    $tree['#attributes']['class'][] = 'nice-menu';
    $tree['#attributes']['class'][] = 'nice-menu-' . $block_config['menu_name'];
    $tree['#attributes']['class'][] = 'nice-menu-' . $block_config['nice_menus_type'];
    $tree['#attributes']['class'][] = 'menu';

    // add 'menuparent' class.
    if (!empty($tree['#items'])) {
      $tree['#items'] = $this
        ->_build_sub_menu_menuparent($tree['#items']);
    }
    return $tree;
  }

  /**
   * @return array
   */
  public function build() {
    $block_config = $this
      ->getBlockConfigExtended();
    $config = \Drupal::config('nice_menus.settings');

    // attach library.
    $library = [];

    // load nice_menus.css
    $library[] = 'nice_menus/nice_menus_css';
    if ($config
      ->get('nice_menus_js')) {
      $library[] = 'nice_menus/superfish';
      $library[] = 'nice_menus/jquery.hoverIntent';
      $library[] = 'nice_menus/nice_menus';
    }

    // load nice menus default css.
    if ($config
      ->get('nice_menus_default_css')) {
      $library[] = 'nice_menus/nice_menus_default';
    }

    // get menu tree.
    $tree = nice_menus_build_tree($block_config);

    // build menu class.
    $tree = $this
      ->_build_menu_style($tree, $block_config);

    /**
     * @TODO suupoert responsive.
     * @TODO display title.
     */
    return array(
      '#theme' => 'nice_menus',
      '#attached' => array(
        'library' => $library,
        'drupalSettings' => array(
          'nice_menus_options' => array(
            'delay' => $config
              ->get('nice_menus_sf_delay'),
            'speed' => $config
              ->get('nice_menus_sf_speed'),
          ),
        ),
      ),
      '#menu_output' => $tree,
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {

    // Even when the menu block renders to the empty string for a user, we want
    // the cache tag for this menu to be set: whenever the menu is changed, this
    // menu block must also be re-rendered for that user, because maybe a menu
    // link that is accessible for that user has been added.
    $cache_tags = parent::getCacheTags();
    $block_config = $this
      ->getBlockConfigExtended();
    $cache_tags[] = 'config:system.menu.' . $block_config['menu_name'];
    return $cache_tags;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {

    // ::build() uses MenuActiveTrail::getActiveTrailIds()
    // to extend menu tree parameters, and those take the active menu trail
    // into account. Therefore, we must vary the rendered menu by the active
    // trail of the rendered menu.
    // Additional cache contexts, e.g. those that determine link text or
    // accessibility of a menu, will be bubbled automatically.
    $block_config = $this
      ->getBlockConfigExtended();
    $menu_name = $block_config['menu_name'];
    return Cache::mergeContexts(parent::getCacheContexts(), [
      'route.menu_active_trails:' . $menu_name,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getBlockConfigExtended() {

    // get config.
    $block_config = $this
      ->getConfiguration();

    // set default menu_name and menu_mlid.
    list($block_config['menu_name'], $block_config['menu_mlid']) = explode(':', $block_config['nice_menus_menu'], 2);
    return $block_config;
  }

}

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
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
NiceMenusBlock::$menuSelector protected property The path alias manager.
NiceMenusBlock::blockForm public function Overrides BlockPluginTrait::blockForm
NiceMenusBlock::blockSubmit public function Overrides BlockPluginTrait::blockSubmit
NiceMenusBlock::build public function Overrides BlockPluginInterface::build
NiceMenusBlock::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
NiceMenusBlock::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
NiceMenusBlock::getBlockConfigExtended public function
NiceMenusBlock::getCacheContexts public function The cache contexts associated with this object. Overrides ContextAwarePluginBase::getCacheContexts
NiceMenusBlock::getCacheTags public function The cache tags associated with this object. Overrides ContextAwarePluginBase::getCacheTags
NiceMenusBlock::_build_menu_style public function add class to nice menus.
NiceMenusBlock::_build_sub_menu_menuparent public function // add 'menuparent' class.
NiceMenusBlock::__construct public function NiceMenusBlock constructor. Overrides BlockPluginTrait::__construct
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.
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