Skip to content

Instantly share code, notes, and snippets.

@japicoder
Created July 12, 2018 14:00
Show Gist options
  • Save japicoder/f6df97d37bf67e713fdbd26298053d62 to your computer and use it in GitHub Desktop.
Save japicoder/f6df97d37bf67e713fdbd26298053d62 to your computer and use it in GitHub Desktop.
Drupal 8 - How to wrap a webform managed file field
<?php
/**
* @file
* Content of the example.module.
* We start with a webform where a "product_complain" file managed field is present.
* Our objective is to wrap this field in a <div> with a custom class.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\example\RenderElementWrapper;
/**
* Implements hook_webform_element_ELEMENT_TYPE_alter() for managed_file.
*/
function example_webform_element_managed_file_alter(array &$element, FormStateInterface $form_state, array $context) {
// Add an extra theme wrapper to our attachment, for an easier styling.
if ($element['#webform_id'] === 'product_complaint--attachment') {
$element['#outer_wrapper'] = TRUE;
}
}
/**
* Implements hook_element_info_alter().
*/
function example_element_info_alter(array &$info) {
\Drupal::classResolver()->getInstanceFromDefinition(RenderElementWrapper::class)
->alterElementInfo($info);
}
<?php
namespace Drupal\example;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides functionality to process render elements.
*/
class RenderElementWrapper {
/**
* Alters the element type info.
*
* Alter the 'process' information for the managed file elements.
*
* @param array $info
* An associative array with structure identical to that of the return value
* of \Drupal\Core\Render\ElementInfoManagerInterface::getInfo().
*/
public function alterElementInfo(array &$info) {
foreach ($info as $element_type => $element_info) {
if ($element_type == 'managed_file') {
$info[$element_type]['#process'][] = [static::class, 'processElement'];
}
}
}
/**
* Process the managed_file elements.
*
* @param array $element
* An associative array containing the properties and children of the
* element. Note that $element must be taken by reference here, so processed
* child elements are taken over into $form_state.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $complete_form
* The complete form structure.
*
* @return array
* The processed element.
*/
public static function processElement(array &$element, FormStateInterface $form_state, array &$complete_form) {
if (!empty($element['#outer_wrapper']) && !$form_state->isRebuilding()) {
$element['#prefix'] = '<div class="managed-file-outer-wrapper">' . $element['#prefix'];
$element['#suffix'] .= '</div>';
}
return $element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment