ex_icons-8.x-1.0/src/Element/ExIconSelect.php

src/Element/ExIconSelect.php
<?php

namespace Drupal\ex_icons\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Radios;

/**
 * Provides a form element for selecting an icon.
 *
 * Usage example:
 * @code
 * $form['icon'] = [
 *   '#type' => 'ex_icon_select',
 *   '#title' => $this->t('Title icon'),
 *   '#default_value' => 'arrow',
 * ];
 * @endcode
 *
 * @see \Drupal\Core\Render\Element\Radios
 *
 * @FormElement("ex_icon_select")
 */
class ExIconSelect extends Radios {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#theme_wrappers' => ['radios__ex_icon_select'],
    ] + parent::getInfo();
  }

  /**
   * {@inheritdoc}
   */
  public static function processRadios(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#options'] = \Drupal::service('ex_icons.manager')->getIconOptions();

    // If not required:
    if (!isset($element['#states']['required']) && !$element['#required']) {
      // Add empty value option.
      $element['#options'] = ['' => t('No icon')] + $element['#options'];

      // Set to empty value if no default value set or previously nulled value.
      if (!isset($element['#default_value']) || $element['#default_value'] === '') {
        $element['#default_value'] = '';
      }
    }

    $element = parent::processRadios($element, $form_state, $complete_form);

    foreach ($element['#options'] as $key => $label) {
      $element[$key]['#attributes']['class'][] = 'visually-hidden';
      $element[$key]['#theme_wrappers'] = ['form_element__ex_icon_select'];
      $element[$key]['#wrapper_attributes']['class'][] = 'ex-icon-select__item';
      $element[$key]['#label_attributes']['class'][] = 'ex-icon-select__radio';

      if ($key != '') {
        $icon = [
          '#theme' => 'ex_icon',
          '#id' => $key,
          '#attributes' => [
            'title' => $label,
            'class' => ['ex-icon-select__icon'],
          ],
        ];
        $element[$key]['#title'] = \Drupal::service('renderer')->render($icon);
      }
    }

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    $element['#options'] = \Drupal::service('ex_icons.manager')->getIconOptions();
    return parent::valueCallback($element, $input, $form_state);
  }

}

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

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