doghouse_menu-3.0.x-dev/modules/doghouse_megamenu/doghouse_megamenu.module

modules/doghouse_megamenu/doghouse_megamenu.module
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function doghouse_megamenu_form_alter(&$form, &$form_state, $form_id) {
  if (!in_array($form_id, ['block_content_doghouse_menu_megamenu_form', 'block_content_doghouse_menu_megamenu_edit_form'])) {
    return;
  }
  $form['#attached']['library'][] = 'doghouse_megamenu/block_content_mega_menu';
}

/**
 * Implements hook_form_menu_link_content_form_alter().
 */
function doghouse_megamenu_form_menu_link_content_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $entity = $form_state->getFormObject()->getEntity();
  $link = $entity->link->first();

  $form['doghouse_megamenu'] = [
    '#type' => 'details',
    '#title' => t('Mega Menu'),
    '#tree' => TRUE,
  ];

  $form['doghouse_megamenu']['block'] = [
    '#type' => 'select',
    '#title' => 'Select a mega menu block',
    '#default_value' => isset($link->options['megamenu_block_id']) ? $link->options['megamenu_block_id'] : '',
    '#options' => _doghouse_megamenu_block_options(),
  ];

  $form['actions']['submit']['#submit'][] = 'doghouse_megamenu_menu_link_content_form_submit';
}

/**
 * Submit handler for new megamenu select options on menu link form.
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function doghouse_megamenu_menu_link_content_form_submit($form, FormStateInterface $form_state) {
  $form_object = $form_state->getFormObject();
  $menu_link = $form_object->getEntity();

  if (!$menu_link->link) {
    return;
  }

  if ($id = $form_state->getValue(['doghouse_megamenu', 'block'])) {
    $options = $menu_link->link->first()->options ?: [];
    $menu_link->link->first()->options = array_merge($options, ['megamenu_block_id' => $id]);
    $menu_link->save();
  }
}

function _doghouse_megamenu_block_options() {
  $nids = \Drupal::entityQuery('block_content')->condition('type','doghouse_menu_megamenu')->execute();
  $blocks = \Drupal::service('entity_type.manager')->getStorage('block_content')->loadMultiple($nids);

  $options = ['' => '- None -'];
  foreach ($blocks as $block) {
    $options[$block->id()] = $block->label();
  }
  return $options;
}

/**
 * Implements hook_theme().
 */
function doghouse_megamenu_theme() {
  return [
    'doghouse_mega_menu_block' => [
      'variables' => [
        'items' => NULL
      ],
      'render element' => 'children',
    ],
  ];
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc