You are here

public static function Micon::processMicon in Micon 2.x

Same name and namespace in other branches
  1. 8 src/Element/Micon.php \Drupal\micon\Element\Micon::processMicon()

Processes an Micon icon form element.

This process callback is mandatory for select fields, since all user agents automatically preselect the first available option of single (non-multiple) select lists.

Parameters

array $element: The form element to process.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

array $complete_form: The complete form structure.

Return value

array The processed element.

See also

_form_validate()

File

src/Element/Micon.php, line 71

Class

Micon
Provides a one-line text field form element.

Namespace

Drupal\micon\Element

Code

public static function processMicon(array &$element, FormStateInterface $form_state, array &$complete_form) {

  // For proper validation we need to override the type as a select field.
  $element['#type'] = 'select';
  $element['#attributes']['class'][] = 'js-hide';
  $element['#options'] = [];

  // If the element is set to #required through #states, override the
  // element's #required setting.
  $required = isset($element['#states']['required']) ? TRUE : $element['#required'];

  // If the element is required and there is no #default_value, then add an
  // empty option that will fail validation, so that the user is required to
  // make a choice. Also, if there's a value for #empty_value or
  // #empty_option, then add an option that represents emptiness.
  if ($required && !isset($element['#default_value']) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
    $element += [
      '#empty_value' => '',
      '#empty_option' => $required ? t('- Select -') : t('- None -'),
    ];

    // The empty option is prepended to #options and purposively not merged
    // to prevent another option in #options mistakenly using the same value
    // as #empty_value.
    $empty_option = [
      $element['#empty_value'] => $element['#empty_option'],
    ];
    $element['#options'] = $empty_option + $element['#options'];
  }
  else {
    $element['#options'][''] = t('- None -');
  }

  // Add icon packages as options.
  $packages = \Drupal::service('micon.icon.manager')
    ->getIcons();
  $include = is_array($element['#packages']) ? array_filter($element['#packages']) : [];
  if (!empty($include)) {
    $packages = array_intersect_key($packages, $include);
  }
  foreach ($packages as $icons) {
    foreach ($icons as $icon) {
      if (count($packages) > 1) {
        $element['#options'][$icon
          ->getPackageLabel()][$icon
          ->getSelector()] = $icon
          ->toJson();
      }
      else {
        $element['#options'][$icon
          ->getSelector()] = $icon
          ->toJson();
      }
    }
  }
  $element['#attached']['library'][] = 'micon/micon.element';
  return $element;
}