You are here

micon_vocabulary.module in Micon 2.x

Same filename and directory in other branches
  1. 8 micon_vocabulary/micon_vocabulary.module

File

micon_vocabulary/micon_vocabulary.module
View source
<?php

/**
 * @file
 * Contains micon_vocabulary.module.
 */
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\VocabularyInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds icon options to the vocabulary form.
 *
 * @see VocabularyForm::form()
 */
function micon_vocabulary_form_taxonomy_vocabulary_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\taxonomy\VocabularyInterface $type */
  $type = $form_state
    ->getFormObject()
    ->getEntity();
  $form['icon'] = [
    '#type' => 'micon',
    '#title' => t('Icon'),
    '#default_value' => micon_vocabulary_icon($type),
    '#weight' => 0,
  ];
  $form['#entity_builders'][] = 'micon_vocabulary_form_taxonomy_vocabulary_form_builder';
}

/**
 * Entity builder for the vocabulary form with menu options.
 *
 * @see menu_ui_form_taxonomy_vocabulary_form_alter()
 */
function micon_vocabulary_form_taxonomy_vocabulary_form_builder($entity_type, VocabularyInterface $type, &$form, FormStateInterface $form_state) {
  $type
    ->setThirdPartySetting('micon_vocabulary', 'icon', $form_state
    ->getValue('icon'));
  Cache::invalidateTags([
    'micon.discovery',
  ]);
}

/**
 * Helper function for retrieving the icon from a vocabulary.
 *
 * @var \Drupal\taxonomy\VocabularyInterface $type
 *   The taxonomy vocabulary.
 */
function micon_vocabulary_icon(VocabularyInterface $type) {
  return $type
    ->getThirdPartySetting('micon_vocabulary', 'icon');
}

/**
 * Implements hook_micon_icons_alter().
 */
function micon_vocabulary_micon_icons_alter(&$icons) {
  $defaults = [
    'text' => '',
    'regex' => '',
    'weight' => 0,
    'provider' => 'micon_vocabulary',
  ];
  $types = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_vocabulary')
    ->loadMultiple();
  foreach ($types as $type) {
    if ($icon = micon_vocabulary_icon($type)) {
      $id = 'vocabulary.' . $type
        ->id();
      $icons[$id] = [
        'text' => 'vocabulary.' . strtolower($type
          ->label()),
        'icon' => $icon,
        'id' => $id,
      ] + $defaults;
    }
  }
}

Functions

Namesort descending Description
micon_vocabulary_form_taxonomy_vocabulary_form_alter Implements hook_form_FORM_ID_alter().
micon_vocabulary_form_taxonomy_vocabulary_form_builder Entity builder for the vocabulary form with menu options.
micon_vocabulary_icon Helper function for retrieving the icon from a vocabulary.
micon_vocabulary_micon_icons_alter Implements hook_micon_icons_alter().