StatusMessages.php 2.58 KB
Newer Older
1 2 3 4 5 6 7
<?php

namespace Drupal\Core\Render\Element;

/**
 * Provides a messages element.
 *
8
 * Used to display results of \Drupal::messenger()->addMessage() calls.
9 10 11 12 13 14
 *
 * Usage example:
 * @code
 * $build['status_messages'] = [
 *   '#type' => 'status_messages',
 * ];
15
 * @endcode
16
 *
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 * @RenderElement("status_messages")
 */
class StatusMessages extends RenderElement {

  /**
   * {@inheritdoc}
   *
   * Generate the placeholder in a #pre_render callback, because the hash salt
   * needs to be accessed, which may not yet be available when this is called.
   */
  public function getInfo() {
    return [
      // May have a value of 'status' or 'error' when only displaying messages
      // of that specific type.
      '#display' => NULL,
      '#pre_render' => [
        get_class() . '::generatePlaceholder',
      ],
    ];
  }

  /**
   * #pre_render callback to generate a placeholder.
   *
   * @param array $element
   *   A renderable array.
   *
   * @return array
   *   The updated renderable array containing the placeholder.
   */
  public static function generatePlaceholder(array $element) {
48
    $element = [
49 50
      '#lazy_builder' => [get_class() . '::renderMessages', [$element['#display']]],
      '#create_placeholder' => TRUE,
51 52
    ];

53 54 55 56
    // Directly create a placeholder as we need this to be placeholdered
    // regardless if this is a POST or GET request.
    // @todo remove this when https://www.drupal.org/node/2367555 lands.
    return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
57 58 59
  }

  /**
60
   * #lazy_builder callback; replaces placeholder with messages.
61
   *
62 63
   * @param string|null $type
   *   Limit the messages returned by type. Defaults to NULL, meaning all types.
64 65
   *   Passed on to \Drupal\Core\Messenger\Messenger::deleteByType(). These
   *   values are supported:
66 67 68 69
   *   - NULL
   *   - 'status'
   *   - 'warning'
   *   - 'error'
70 71 72
   *
   * @return array
   *   A renderable array containing the messages.
73
   *
74
   * @see \Drupal\Core\Messenger\Messenger::deleteByType()
75
   */
76
  public static function renderMessages($type = NULL) {
77
    $render = [];
78 79 80 81 82 83 84
    if (isset($type)) {
      $messages = \Drupal::messenger()->deleteByType($type);
    }
    else {
      $messages = \Drupal::messenger()->deleteAll();
    }

85 86 87 88 89 90 91 92 93 94 95 96 97
    if ($messages) {
      // Render the messages.
      $render = [
        '#theme' => 'status_messages',
        '#message_list' => $messages,
        '#status_headings' => [
          'status' => t('Status message'),
          'error' => t('Error message'),
          'warning' => t('Warning message'),
        ],
      ];
    }
    return $render;
98 99 100
  }

}