3 namespace Drupal\Core\Render\Element;
5 use Drupal\Core\Form\FormBuilderInterface;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Plugin\PluginBase;
8 use Drupal\Core\Render\BubbleableMetadata;
9 use Drupal\Core\Render\Element;
13 * Provides a base class for render element plugins.
15 * Render elements are referenced in render arrays; see the
16 * @link theme_render Render API topic @endlink for an overview of render
17 * arrays and render elements.
19 * The elements of render arrays are divided up into properties (whose keys
20 * start with #) and children (whose keys do not start with #). The properties
21 * provide data or settings that are used in rendering. Some properties are
22 * specific to a particular type of render element, some are available for any
23 * render element, and some are available for any form input element. A list of
24 * the properties that are available for all render elements follows; the
25 * properties that are for all form elements are documented on
26 * \Drupal\Core\Render\Element\FormElement, and properties specific to a
27 * particular element are documented on that element's class. See the
28 * @link theme_render Render API topic @endlink for a list of the most
29 * commonly-used properties.
31 * Many of the properties are strings that are displayed to users. These
32 * strings, if they are literals provided by your module, should be
33 * internationalized and translated; see the
34 * @link i18n Internationalization topic @endlink for more information. Note
35 * that although in the properies list that follows, they are designated to be
36 * of type string, they would generally end up being
37 * \Drupal\Core\StringTranslation\TranslatableMarkup objects instead.
39 * Here is the list of the properties used during the rendering of all render
41 * - #access: (bool) Whether the element is accessible or not. When FALSE,
42 * the element is not rendered and user-submitted values are not taken
44 * - #access_callback: A callable or function name to call to check access.
46 * - #allowed_tags: (array) Array of allowed HTML tags for XSS filtering of
47 * #markup, #prefix, #suffix, etc.
48 * - #attached: (array) Array of attachments associated with the element.
49 * See the "Attaching libraries in render arrays" section of the
50 * @link theme_render Render API topic @endlink for an overview, and
51 * \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments
52 * for a list of what this can contain. Besides this list, it may also contain
53 * a 'placeholders' element; see the Placeholders section of the
54 * @link theme_render Render API topic @endlink for an overview.
55 * - #attributes: (array) HTML attributes for the element. The first-level
56 * keys are the attribute names, such as 'class', and the attributes are
57 * usually given as an array of string values to apply to that attribute
58 * (the rendering system will concatenate them together into a string in
60 * - #cache: (array) Cache information. See the Caching section of the
61 * @link theme_render Render API topic @endlink for more information.
62 * - #children: (array, internal) Array of child elements of this element.
63 * Set and used during the rendering process.
64 * - #create_placeholder: (bool) TRUE if the element has placeholders that
65 * are generated by #lazy_builder callbacks. Set internally during rendering
66 * in some cases. See also #attached.
67 * - #defaults_loaded: (bool) Set to TRUE during rendering when the defaults
68 * for the element #type have been added to the element.
69 * - #id: (string) The HTML ID on the element. This is automatically set for
70 * form elements, but not for all render elements; you can override the
71 * default value or add an ID by setting this property.
72 * - #lazy_builder: (array) Array whose first element is a lazy building
73 * callback (callable), and whose second is an array of scalar arguments to
74 * the callback. To use lazy building, the element array must be very
75 * simple: no properties except #lazy_builder, #cache, #weight, and
76 * #create_placeholder, and no children. A lazy builder callback typically
77 * generates #markup and/or placeholders; see the Placeholders section of the
78 * @link theme_render Render API topic @endlink for information about
80 * - #markup: (string) During rendering, this will be set to the HTML markup
81 * output. It can also be set on input, as a fallback if there is no
82 * theming for the element. This will be filtered for XSS problems during
83 * rendering; see also #plain_text and #allowed_tags.
84 * - #plain_text: (string) Elements can set this instead of #markup. All HTML
85 * tags will be escaped in this text, and if both #plain_text and #markup
86 * are provided, #plain_text is used.
87 * - #post_render: (array) Array of callables or function names, which are
88 * called after the element is rendered. Arguments: rendered element string,
90 * - #pre_render: (array) Array of callables or function names, which are
91 * called just before the element is rendered. Argument: $element.
92 * Return value: an altered $element.
93 * - #prefix: (string) Text to render before the entire element output. See
94 * also #suffix. If it is not already wrapped in a safe markup object, will
95 * be filtered for XSS safety.
96 * - #printed: (bool, internal) Set to TRUE when an element and its children
98 * - #render_children: (bool, internal) Set to FALSE by the rendering process
99 * if the #theme call should be bypassed (normally, the theme is used to
100 * render the children). Set to TRUE by the rendering process if the children
101 * should be rendered by rendering each one separately and concatenating.
102 * - #suffix: (string) Text to render after the entire element output. See
103 * also #prefix. If it is not already wrapped in a safe markup object, will
104 * be filtered for XSS safety.
105 * - #theme: (string) Name of the theme hook to use to render the element.
106 * A default is generally set for elements; users of the element can
107 * override this (typically by adding __suggestion suffixes).
108 * - #theme_wrappers: (array) Array of theme hooks, which are invoked
109 * after the element and children are rendered, and before #post_render
111 * - #type: (string) The machine name of the type of render/form element.
112 * - #weight: (float) The sort order for rendering, with lower numbers coming
113 * before higher numbers. Default if not provided is zero; elements with
114 * the same weight are rendered in the order they appear in the render
117 * @see \Drupal\Core\Render\Annotation\RenderElement
118 * @see \Drupal\Core\Render\ElementInterface
119 * @see \Drupal\Core\Render\ElementInfoManager
122 * @ingroup theme_render
124 abstract class RenderElement extends PluginBase implements ElementInterface {
129 public static function setAttributes(&$element, $class = []) {
130 if (!empty($class)) {
131 if (!isset($element['#attributes']['class'])) {
132 $element['#attributes']['class'] = [];
134 $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
136 // This function is invoked from form element theme functions, but the
137 // rendered form element may not necessarily have been processed by
138 // \Drupal::formBuilder()->doBuildForm().
139 if (!empty($element['#required'])) {
140 $element['#attributes']['class'][] = 'required';
141 $element['#attributes']['required'] = 'required';
142 $element['#attributes']['aria-required'] = 'true';
144 if (isset($element['#parents']) && isset($element['#errors']) && !empty($element['#validated'])) {
145 $element['#attributes']['class'][] = 'error';
146 $element['#attributes']['aria-invalid'] = 'true';
151 * Adds members of this group as actual elements for rendering.
153 * @param array $element
154 * An associative array containing the properties and children of the
158 * The modified element with all group members.
160 public static function preRenderGroup($element) {
161 // The element may be rendered outside of a Form API context.
162 if (!isset($element['#parents']) || !isset($element['#groups'])) {
166 // Inject group member elements belonging to this group.
167 $parents = implode('][', $element['#parents']);
168 $children = Element::children($element['#groups'][$parents]);
169 if (!empty($children)) {
170 foreach ($children as $key) {
171 // Break references and indicate that the element should be rendered as
173 $child = (array) $element['#groups'][$parents][$key];
174 $child['#group_details'] = TRUE;
175 // Inject the element as new child element.
180 // Re-sort the element's children if we injected group member elements.
182 $element['#sorted'] = FALSE;
186 if (isset($element['#group'])) {
187 // Contains form element summary functionalities.
188 $element['#attached']['library'][] = 'core/drupal.form';
190 $group = $element['#group'];
191 // If this element belongs to a group, but the group-holding element does
192 // not exist, we need to render it (at its original location).
193 if (!isset($element['#groups'][$group]['#group_exists'])) {
194 // Intentionally empty to clarify the flow; we simply return $element.
196 // If we injected this element into the group, then we want to render it.
197 elseif (!empty($element['#group_details'])) {
198 // Intentionally empty to clarify the flow; we simply return $element.
200 // Otherwise, this element belongs to a group and the group exists, so we do
202 elseif (Element::children($element['#groups'][$group])) {
203 $element['#printed'] = TRUE;
211 * Form element processing handler for the #ajax form property.
213 * This method is useful for non-input elements that can be used in and
214 * outside the context of a form.
216 * @param array $element
217 * An associative array containing the properties of the element.
218 * @param \Drupal\Core\Form\FormStateInterface $form_state
219 * The current state of the form.
220 * @param array $complete_form
221 * The complete form structure.
224 * The processed element.
226 * @see self::preRenderAjaxForm()
228 public static function processAjaxForm(&$element, FormStateInterface $form_state, &$complete_form) {
229 return static::preRenderAjaxForm($element);
233 * Adds Ajax information about an element to communicate with JavaScript.
235 * If #ajax is set on an element, this additional JavaScript is added to the
236 * page header to attach the Ajax behaviors. See ajax.js for more information.
238 * @param array $element
239 * An associative array containing the properties of the element.
244 * - #ajax['callback']
247 * - #ajax['parameters']
252 * The processed element with the necessary JavaScript attached to it.
254 public static function preRenderAjaxForm($element) {
255 // Skip already processed elements.
256 if (isset($element['#ajax_processed'])) {
259 // Initialize #ajax_processed, so we do not process this element again.
260 $element['#ajax_processed'] = FALSE;
262 // Nothing to do if there are no Ajax settings.
263 if (empty($element['#ajax'])) {
267 // Add a data attribute to disable automatic refocus after ajax call.
268 if (!empty($element['#ajax']['disable-refocus'])) {
269 $element['#attributes']['data-disable-refocus'] = "true";
272 // Add a reasonable default event handler if none was specified.
273 if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
274 switch ($element['#type']) {
278 // Pressing the ENTER key within a textfield triggers the click event of
279 // the form's first submit button. Triggering Ajax in this situation
280 // leads to problems, like breaking autocomplete textfields, so we bind
281 // to mousedown instead of click.
282 // @see https://www.drupal.org/node/216059
283 $element['#ajax']['event'] = 'mousedown';
284 // Retain keyboard accessibility by setting 'keypress'. This causes
285 // ajax.js to trigger 'event' when SPACE or ENTER are pressed while the
287 $element['#ajax']['keypress'] = TRUE;
288 // Binding to mousedown rather than click means that it is possible to
289 // trigger a click by pressing the mouse, holding the mouse button down
290 // until the Ajax request is complete and the button is re-enabled, and
291 // then releasing the mouse button. Set 'prevent' so that ajax.js binds
292 // an additional handler to prevent such a click from triggering a
293 // non-Ajax form submission. This also prevents a textfield's ENTER
294 // press triggering this button's non-Ajax form submission behavior.
295 if (!isset($element['#ajax']['prevent'])) {
296 $element['#ajax']['prevent'] = 'click';
305 $element['#ajax']['event'] = 'blur';
311 $element['#ajax']['event'] = 'change';
315 $element['#ajax']['event'] = 'click';
323 // Attach JavaScript settings to the element.
324 if (isset($element['#ajax']['event'])) {
325 $element['#attached']['library'][] = 'core/jquery.form';
326 $element['#attached']['library'][] = 'core/drupal.ajax';
328 $settings = $element['#ajax'];
330 // Assign default settings. When 'url' is set to NULL, ajax.js submits the
331 // Ajax request to the same URL as the form or link destination is for
332 // someone with JavaScript disabled. This is generally preferred as a way to
333 // ensure consistent server processing for js and no-js users, and Drupal's
334 // content negotiation takes care of formatting the response appropriately.
335 // However, 'url' and 'options' may be set when wanting server processing
336 // to be substantially different for a JavaScript triggered submission.
339 'options' => ['query' => []],
340 'dialogType' => 'ajax',
342 if (array_key_exists('callback', $settings) && !isset($settings['url'])) {
343 $settings['url'] = Url::fromRoute('<current>');
344 // Add all the current query parameters in order to ensure that we build
345 // the same form on the AJAX POST requests. For example,
346 // \Drupal\user\AccountForm takes query parameters into account in order
347 // to hide the password field dynamically.
348 $settings['options']['query'] += \Drupal::request()->query->all();
349 $settings['options']['query'][FormBuilderInterface::AJAX_FORM_REQUEST] = TRUE;
352 // @todo Legacy support. Remove in Drupal 8.
353 if (isset($settings['method']) && $settings['method'] == 'replace') {
354 $settings['method'] = 'replaceWith';
357 // Convert \Drupal\Core\Url object to string.
358 if (isset($settings['url']) && $settings['url'] instanceof Url) {
359 $url = $settings['url']->setOptions($settings['options'])->toString(TRUE);
360 BubbleableMetadata::createFromRenderArray($element)
363 $settings['url'] = $url->getGeneratedUrl();
366 $settings['url'] = NULL;
368 unset($settings['options']);
370 // Add special data to $settings['submit'] so that when this element
371 // triggers an Ajax submission, Drupal's form processing can determine which
372 // element triggered it.
373 // @see _form_element_triggered_scripted_submission()
374 if (isset($settings['trigger_as'])) {
375 // An element can add a 'trigger_as' key within #ajax to make the element
376 // submit as though another one (for example, a non-button can use this
377 // to submit the form as though a button were clicked). When using this,
378 // the 'name' key is always required to identify the element to trigger
379 // as. The 'value' key is optional, and only needed when multiple elements
380 // share the same name, which is commonly the case for buttons.
381 $settings['submit']['_triggering_element_name'] = $settings['trigger_as']['name'];
382 if (isset($settings['trigger_as']['value'])) {
383 $settings['submit']['_triggering_element_value'] = $settings['trigger_as']['value'];
385 unset($settings['trigger_as']);
387 elseif (isset($element['#name'])) {
388 // Most of the time, elements can submit as themselves, in which case the
389 // 'trigger_as' key isn't needed, and the element's name is used.
390 $settings['submit']['_triggering_element_name'] = $element['#name'];
391 // If the element is a (non-image) button, its name may not identify it
392 // uniquely, in which case a match on value is also needed.
393 // @see _form_button_was_clicked()
394 if (!empty($element['#is_button']) && empty($element['#has_garbage_value'])) {
395 $settings['submit']['_triggering_element_value'] = $element['#value'];
399 // Convert a simple #ajax['progress'] string into an array.
400 if (isset($settings['progress']) && is_string($settings['progress'])) {
401 $settings['progress'] = ['type' => $settings['progress']];
403 // Change progress path to a full URL.
404 if (isset($settings['progress']['url']) && $settings['progress']['url'] instanceof Url) {
405 $settings['progress']['url'] = $settings['progress']['url']->toString();
408 $element['#attached']['drupalSettings']['ajax'][$element['#id']] = $settings;
409 $element['#attached']['drupalSettings']['ajaxTrustedUrl'][$settings['url']] = TRUE;
411 // Indicate that Ajax processing was successful.
412 $element['#ajax_processed'] = TRUE;
418 * Arranges elements into groups.
420 * This method is useful for non-input elements that can be used in and
421 * outside the context of a form.
423 * @param array $element
424 * An associative array containing the properties and children of the
425 * element. Note that $element must be taken by reference here, so processed
426 * child elements are taken over into $form_state.
427 * @param \Drupal\Core\Form\FormStateInterface $form_state
428 * The current state of the form.
429 * @param array $complete_form
430 * The complete form structure.
433 * The processed element.
435 public static function processGroup(&$element, FormStateInterface $form_state, &$complete_form) {
436 $parents = implode('][', $element['#parents']);
438 // Each details element forms a new group. The #type 'vertical_tabs' basically
439 // only injects a new details element.
440 $groups = &$form_state->getGroups();
441 $groups[$parents]['#group_exists'] = TRUE;
442 $element['#groups'] = &$groups;
444 // Process vertical tabs group member details elements.
445 if (isset($element['#group'])) {
446 // Add this details element to the defined group (by reference).
447 $group = $element['#group'];
448 $groups[$group][] = &$element;