How to customize the text for a file (upload) input
Last updated on
25 July 2017
Below code is inspired by https://stackoverflow.com/questions/21842274/cross-browser-custom-stylin...
/**
* Implements template_preprocess_file_managed_file().
*
* Below code snippet replaces the file upload element with a click label that
* is styled as a button.
*
* @see https://stackoverflow.com/questions/21842274/cross-browser-custom-styling-for-file-upload-button
* @see template_preprocess_file_managed_file().
*/
function MYMODULE_preprocess_file_managed_file(&$variables) {
// Don't alter hidden file upload input.
if (isset($variables['element']['upload']['#access']) && $variables['element']['upload']['#access'] === FALSE) {
return;
}
// Create an unique id for the file upload input and label.
$id = \Drupal\Component\Utility\Html::getUniqueId($variables['element']['upload']['#id'] . '-target');
// Create a label that is styled like an action button.
$label = [
'#type' => 'html_tag',
'#tag' => 'label',
'#value' => t('Select a file'),
'#attributes' => [
'for' => $id,
'class' => 'button button-action'
],
];
// Make sure the label is first.
$variables['element'] = ['label' => $label] + $variables['element'];
// Set the custom ID for file upload input.
$variables['element']['upload']['#attributes']['id'] = $id;
// Hide the file upload.
$variables['element']['upload']['#attributes']['style'] = 'position: fixed; top: -1000px;';
}
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion