Be a happy coder

You are here

Wrap a webform managed file field into a <div> with custom class

12 Jul 2018

In this short article I'll show how to wrap a managed file field into a <div>.

The motivation is that sometimes we need to apply some styling to our field, but considering this sort of field changes it's structure everytime we upload or remove a file, it makes more difficult to apply the CSS correctly. For that reason, a

that wraps all the content that Drupal's AJAX call will replace comes very handy here.

This shouldn't that difficult except for the fact that the field changes on every AJAX call it does. If we take a look to the file module, we can see that the field is prefixed with a <div id="ajax-wrapper"> wrapper. This is done by Drupal\file\Element\ManagedFile.php class, at the processManagedFile() method, and if you try to alter this prefix at any preprocess function, you'll see that the prefix value remains unchanged, despite our efforts.

At the end, I came up to the conclusion that I should add my custom wrapper on a #process call for the form element, then I implemented a hook_element_info_alter() function to insert my custom process function. Apart from that, I wanted to apply my wrapper only on a specific situation, so I implemented another function for a hook_webform_element_ELEMENT_TYPE_alter() hook to flag the managed field that I want to get flagged. Finally, my RenderElementWrapper will provide the extra process method that will check if the form is not being rebuilt (like during AJAX calls) and then, when the correct field requires it, add my custom wrapper.

Here's a gist with the example: