Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / StatusMessages.php
1 <?php
2
3 namespace Drupal\Core\Render\Element;
4
5 /**
6  * Provides a messages element.
7  *
8  * Used to display results of drupal_set_message() calls.
9  *
10  * Usage example:
11  * @code
12  * $build['status_messages'] = [
13  *   '#type' => 'status_messages',
14  * ];
15  * @endcode
16  *
17  * @RenderElement("status_messages")
18  */
19 class StatusMessages extends RenderElement {
20
21   /**
22    * {@inheritdoc}
23    *
24    * Generate the placeholder in a #pre_render callback, because the hash salt
25    * needs to be accessed, which may not yet be available when this is called.
26    */
27   public function getInfo() {
28     return [
29       // May have a value of 'status' or 'error' when only displaying messages
30       // of that specific type.
31       '#display' => NULL,
32       '#pre_render' => [
33         get_class() . '::generatePlaceholder',
34       ],
35     ];
36   }
37
38   /**
39    * #pre_render callback to generate a placeholder.
40    *
41    * @param array $element
42    *   A renderable array.
43    *
44    * @return array
45    *   The updated renderable array containing the placeholder.
46    */
47   public static function generatePlaceholder(array $element) {
48     $element = [
49       '#lazy_builder' => [get_class() . '::renderMessages', [$element['#display']]],
50       '#create_placeholder' => TRUE,
51     ];
52
53     // Directly create a placeholder as we need this to be placeholdered
54     // regardless if this is a POST or GET request.
55     // @todo remove this when https://www.drupal.org/node/2367555 lands.
56     return \Drupal::service('render_placeholder_generator')->createPlaceholder($element);
57   }
58
59   /**
60    * #lazy_builder callback; replaces placeholder with messages.
61    *
62    * @param string|null $type
63    *   Limit the messages returned by type. Defaults to NULL, meaning all types.
64    *   Passed on to drupal_get_messages(). These values are supported:
65    *   - NULL
66    *   - 'status'
67    *   - 'warning'
68    *   - 'error'
69    *
70    * @return array
71    *   A renderable array containing the messages.
72    *
73    * @see drupal_get_messages()
74    */
75   public static function renderMessages($type) {
76     // Render the messages.
77     return [
78       '#theme' => 'status_messages',
79       // @todo Improve when https://www.drupal.org/node/2278383 lands.
80       '#message_list' => drupal_get_messages($type),
81       '#status_headings' => [
82         'status' => t('Status message'),
83         'error' => t('Error message'),
84         'warning' => t('Warning message'),
85       ],
86     ];
87   }
88
89 }