You are here

protected function Select2BoxesAutocompleteListWidget::includeFlagsIcons in Select2 Boxes 8

Include flags icons to the options.

If the "Include flag icons" option is enabled.

Parameters

array &$element: Element's render array.

1 call to Select2BoxesAutocompleteListWidget::includeFlagsIcons()
Select2BoxesAutocompleteListWidget::formElement in src/Plugin/Field/FieldWidget/Select2BoxesAutocompleteListWidget.php
Returns the form for a single field widget.

File

src/Plugin/Field/FieldWidget/Select2BoxesAutocompleteListWidget.php, line 97

Class

Select2BoxesAutocompleteListWidget
Class Select2BoxesAutocompleteList.

Namespace

Drupal\select2boxes\Plugin\Field\FieldWidget

Code

protected function includeFlagsIcons(array &$element) {

  // Include flags is only possible if flags module enabled,
  // field type is one of the 'language_field', 'language', 'country'
  // and an appropriate setting in the fields widget form has been enabled.
  $types = [
    'language_field',
    'language',
    'country',
  ];
  if (\Drupal::moduleHandler()
    ->moduleExists('flags') && in_array($this->fieldDefinition
    ->getType(), $types) && $this
    ->getThirdPartySetting('select2boxes', 'enable_flags') == '1') {

    // Create a map of country or language dependent classes.
    $flags = [];
    $mapper = $this->fieldDefinition
      ->getType() == 'country' ? \Drupal::service('flags.mapping.country') : \Drupal::service('flags.mapping.language');
    foreach (array_keys($element['#options']) as $key) {
      $flags[$key] = [
        'flag',
        'flag-' . $mapper
          ->map($key),
        $mapper
          ->getExtraClasses()[0],
      ];
    }

    // Merge these values to have all countries
    // and languages flags in the same place to prevent missing flags icons.
    if (!isset($element['#attached']['drupalSettings']['flagsClasses'])) {
      $element['#attached']['drupalSettings']['flagsClasses'] = [];
    }
    $element['#attached']['drupalSettings']['flagsClasses'] += $flags;
    $element['#attached']['drupalSettings']['flagsFields'][$this->fieldDefinition
      ->getName()] = TRUE;
    $element['#attached']['library'][] = 'flags/flags';
  }
}