You are here

function webform_preprocess_file_managed_file in Webform 8.5

Same name and namespace in other branches
  1. 6.x includes/webform.theme.inc \webform_preprocess_file_managed_file()

Implements hook_preprocess_file_managed_file() for file managed file templates.

See also

https://stackoverflow.com/questions/21842274/cross-browser-custom-stylin...

template_preprocess_file_managed_file()

File

includes/webform.theme.inc, line 580
Theme hooks, preprocessor, and suggestions.

Code

function webform_preprocess_file_managed_file(&$variables) {
  if (!WebformElementHelper::isWebformElement($variables['element'])) {
    return;
  }
  $element =& $variables['element'];
  if (empty($element['#button'])) {
    return;
  }

  // Don't alter hidden file upload input.
  if (!Element::isVisibleElement($element['upload'])) {
    return;
  }

  // Create an unique id for the file upload input and label.
  $button_id = Html::getUniqueId($variables['element']['upload']['#id'] . '-button');

  // Create a label that is styled like an action button.
  $label = [
    '#type' => 'html_tag',
    '#tag' => 'label',
    '#value' => isset($element['#button__title']) ? $element['#button__title'] : (empty($element['#multiple']) ? t('Choose file') : t('Choose files')),
    '#attributes' => isset($element['#button__attributes']) ? $element['#button__attributes'] : [],
  ];

  // Add 'for' attribute.
  $label['#attributes']['for'] = $button_id;

  // Add default button classes.
  if (empty($label['#attributes']['class'])) {
    $label['#attributes']['class'][] = 'button';
    $label['#attributes']['class'][] = 'button-action';
  }

  // Add .webform-file-button.
  $label['#attributes']['class'][] = 'webform-file-button';

  // Make sure the label is first.
  $element = [
    'label' => $label,
  ] + $element;

  // Set the custom button ID for file upload input.
  $element['upload']['#attributes']['id'] = $button_id;

  // Hide the file upload.
  $element['upload']['#attributes']['class'][] = 'webform-file-button-input';

  // Attach library.
  $element['#attached']['library'][] = 'webform/webform.element.file.button';
}