You are here

function template_preprocess_multiselect in Multiselect 8

Same name and namespace in other branches
  1. 2.x multiselect.module \template_preprocess_multiselect()

Prepares variables for multiselect element templates.

Default template: multiselect.html.twig.

Parameters

array &$variables: An associative array containing:

  • element: An associative array containing the properties of the element. Properties used: #title, #value, #options, #description, #extra, #multiple, #required, #name, #attributes, #size.

File

./multiselect.module, line 69
Select multiple items in an easier way than the normal node-reference widget.

Code

function template_preprocess_multiselect(array &$variables) {
  $element = $variables['element'];
  Element::setAttributes($element, [
    'id',
    'name',
    'size',
    'required',
  ]);
  $available_options = Multiselect::getOptions('available', $element);
  $available_size = min(count($available_options), 10);
  $selected_options = Multiselect::getOptions('selected', $element);
  $selected_size = min(count($selected_options), 10);
  $total_size = $available_size + $selected_size;
  $variables['multiselect'] = [
    'available' => [
      'id' => $element['#attributes']['id'] . '-available',
      'label' => t('Available Options'),
      'attributes' => [
        'id' => $element['#attributes']['id'] . '-available',
        'size' => $total_size,
      ],
      'options' => $available_options,
    ],
    'selected' => [
      'id' => $element['#attributes']['id'],
      'label' => t('Selected Options'),
      'attributes' => $element['#attributes'],
      'options' => $selected_options,
    ],
    'labels' => [
      'add' => t('Add'),
      'remove' => t('Remove'),
    ],
  ];

  // Prepare selected attributes.
  $variables['multiselect']['selected']['attributes']['size'] = $total_size;

  // Prepare attributes for available select.
  foreach ([
    'multiple',
    'class',
  ] as $key) {
    $element_key = "#{$key}";
    if (isset($element[$element_key])) {
      $variables['multiselect']['available']['attributes'][$key] = $element[$element_key];
    }
  }

  // Prepare attributes.
  $multiselect =& $variables['multiselect'];
  foreach ([
    'available',
    'selected',
  ] as $key) {
    $multiselect[$key]['attributes']['class'][] = 'multiselect-' . $key;
    $multiselect[$key]['attributes']['class'][] = 'form-multiselect';
    if (isset($multiselect[$key]['attributes']) && !$multiselect[$key]['attributes'] instanceof Attribute) {
      if ($multiselect[$key]['attributes']) {
        $multiselect[$key]['attributes'] = new Attribute($multiselect[$key]['attributes']);
      }
    }
  }
}