Advertising sustains the DA. Ads are hidden for members. Join today

Webform Cookbook

How to move status messages under a multi-step wizard's progress bar

Last updated on
20 August 2021

You can add '#type': status_messages to your form elements' source view. (see the attached webform)

This approach will create duplicate messages. (see below)

The solution to this problem would be to make sure the webform's status messages purge all messages using the below hook in a CUSTOM_MODULE.

use Drupal\CUSTOM_MODULE\CUSTOM_MODULEformWebformElementStatusMessage;

/**
 * Implements webform_element_alter().
 */
function CUSTOM_MODULE_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  if (isset($element['#type']) && $element['#type'] === 'status_messages') {
    $element['#pre_render'][] = [CUSTOM_MODULEWebformElementStatusMessage::class, 'preRender'];
  }
}

Create a new class which implements TrustedCallbackInterface.

<?php

namespace Drupal\CUSTOM_MODULE;

use Drupal\Core\Security\TrustedCallbackInterface;

/**
 * Provides a trusted callback.
 */
class CUSTOM_MODULEWebformElementStatusMessage implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return ['preRender'];
  }

  /**
   * Pre render callback to display status messages element.
   */
  public static function preRender($element) {
    $messenger = \Drupal::messenger();
    // Replace the status messages placeholder with the rendered messages.
    // Calling $messenger->deleteAll() will purge all messages, which 
    // prevent the messages block from being displayed.
    // @see \Drupal\Core\Render\Element\StatusMessages
    // @see \Drupal\Core\Messenger\MessengerInterfaace
    $element = [
      '#theme' => 'status_messages',
      '#message_list' => $messenger->deleteAll(),
      '#status_headings' => [
        'status' => t('Status message'),
        'error' => t('Error message'),
        'warning' => t('Warning message'),
      ],
    ];
    return $element;
  }

}

Below is a screenshot of the status messages being displayed below the progress bar.

Help improve this page

Page status: No known problems

You can: