You are here

protected static function Select2Boxes::includeIcons in Select2 Boxes 8

Include flags icons.

Parameters

array &$form: Form array.

array $filter_definition: Filter's definition data.

string $key: Element's key.

1 call to Select2Boxes::includeIcons()
Select2Boxes::exposedFormAlter in modules/select2_bef/src/Plugin/better_exposed_filters/filter/Select2Boxes.php

File

modules/select2_bef/src/Plugin/better_exposed_filters/filter/Select2Boxes.php, line 175

Class

Select2Boxes
Default widget implementation.

Namespace

Drupal\select2_bef\Plugin\better_exposed_filters\filter

Code

protected static function includeIcons(array &$form, array $filter_definition, $key) {

  // Create a map of country or language dependent classes.
  $flags = [];

  // Get some additional data from the filter's definition data array.
  $field_name = isset($filter_definition['field_name']) ? $filter_definition['field_name'] : $filter_definition['entity field'];
  $entity_type = $filter_definition['entity_type'];

  // Get the field's definition object to know the field's type.

  /** @var \Drupal\Core\Field\FieldDefinitionInterface $definition */
  $definition = \Drupal::service('entity_field.manager')
    ->getFieldStorageDefinitions($entity_type)[$field_name];

  // Use an appropriate mapper service relatively to the field's type.
  $mapper = !is_null($definition) && $definition
    ->getType() == 'country' ? \Drupal::service('flags.mapping.country') : \Drupal::service('flags.mapping.language');
  foreach (array_keys($form[$key]['#options']) as $key) {
    if ($key == '***LANGUAGE_language_interface***' || $key == '***LANGUAGE_site_default***') {
      continue;
    }
    $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($form['#attached']['drupalSettings']['flagsClasses'])) {
    $form['#attached']['drupalSettings']['flagsClasses'] = [];
  }
  $form['#attached']['drupalSettings']['flagsClasses'] += $flags;

  // We have to use field's column name for views,
  // e.g. FIELD_NAME_value instead of FIELD_NAME.
  // Note: small workaround for the entity properties like langcode.
  if (!isset($filter_definition['field'])) {
    $filter_definition['field'] = $filter_definition['entity field'];
  }
  $form['#attached']['drupalSettings']['flagsFields'][$filter_definition['field']] = TRUE;

  // Attach the flags library.
  $form['#attached']['library'][] = 'flags/flags';
}