0

I want to theme all the file upload fields on my site but I don't know how to name the template file.

I want to alter the form-element.html.twig file but as I have multiple file fields I don't think that the best way is to create theme files for each field. So I was thinking to create a theme based on the field type. Is that possible?

I used the hook_theme_suggestions_input_alter.

function MY_MODULE_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strcmp($element['#type'],'file') == 0) {
    $suggestions[] = 'form-element--file';
  }
}

After clearing the caches seems that doesn't work.

Is this the correct way or is there any other way?

0

As suggested by Ivan Jaros, you can override input--file.html.twig if you want to use twig templates. Basic input template is as follow:

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

If you need to add more dynamic variables, you can use template_preprocess_input() preprocess function.

Also, you can use debug: true under twig.config in services.yml. This will help for theme-related development.

Note: Drupal provides default classes that are from generic to specific to the field. If generic classes helps to theme, I would suggest to avoid all the above.

  • Thank you. That's fine. I already used the classes but what I really want to do is to display the uploaded files below the input field. Also as I have enabled the multiple upload, I get the label in a summary tag and in the actual label tag, I get the 'Add new file', so I also want to change this. FYI, I display the node edit form in a block. – Ismini Jul 3 '17 at 12:35
  • I would suggest using theme function to fetch the temporary uploaded files. Save it in a variable. Use the variable in twig template to render the files. – Vishal Kumar Jul 4 '17 at 1:37
  • And when a user uploads a file using javascript to place it in the correct div? Also using this way (which is interesting) I should also hide the other existing rendered files (using css?). – Ismini Jul 4 '17 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.