annotate core/includes/form.inc @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Functions for form and batch generation and processing.
Chris@0 6 */
Chris@0 7
Chris@0 8 use Drupal\Component\Utility\UrlHelper;
Chris@0 9 use Drupal\Core\Render\Element;
Chris@0 10 use Drupal\Core\Render\Element\RenderElement;
Chris@0 11 use Drupal\Core\Template\Attribute;
Chris@0 12 use Drupal\Core\Url;
Chris@0 13 use Symfony\Component\HttpFoundation\RedirectResponse;
Chris@0 14
Chris@0 15 /**
Chris@0 16 * Prepares variables for select element templates.
Chris@0 17 *
Chris@0 18 * Default template: select.html.twig.
Chris@0 19 *
Chris@0 20 * It is possible to group options together; to do this, change the format of
Chris@0 21 * $options to an associative array in which the keys are group labels, and the
Chris@0 22 * values are associative arrays in the normal $options format.
Chris@0 23 *
Chris@0 24 * @param $variables
Chris@0 25 * An associative array containing:
Chris@0 26 * - element: An associative array containing the properties of the element.
Chris@0 27 * Properties used: #title, #value, #options, #description, #extra,
Chris@0 28 * #multiple, #required, #name, #attributes, #size.
Chris@0 29 */
Chris@0 30 function template_preprocess_select(&$variables) {
Chris@0 31 $element = $variables['element'];
Chris@0 32 Element::setAttributes($element, ['id', 'name', 'size']);
Chris@0 33 RenderElement::setAttributes($element, ['form-select']);
Chris@0 34
Chris@0 35 $variables['attributes'] = $element['#attributes'];
Chris@0 36 $variables['options'] = form_select_options($element);
Chris@0 37 }
Chris@0 38
Chris@0 39 /**
Chris@0 40 * Converts an options form element into a structured array for output.
Chris@0 41 *
Chris@0 42 * This function calls itself recursively to obtain the values for each optgroup
Chris@0 43 * within the list of options and when the function encounters an object with
Chris@0 44 * an 'options' property inside $element['#options'].
Chris@0 45 *
Chris@0 46 * @param array $element
Chris@0 47 * An associative array containing the following key-value pairs:
Chris@0 48 * - #multiple: Optional Boolean indicating if the user may select more than
Chris@0 49 * one item.
Chris@0 50 * - #options: An associative array of options to render as HTML. Each array
Chris@0 51 * value can be a string, an array, or an object with an 'option' property:
Chris@0 52 * - A string or integer key whose value is a translated string is
Chris@0 53 * interpreted as a single HTML option element. Do not use placeholders
Chris@0 54 * that sanitize data: doing so will lead to double-escaping. Note that
Chris@0 55 * the key will be visible in the HTML and could be modified by malicious
Chris@0 56 * users, so don't put sensitive information in it.
Chris@0 57 * - A translated string key whose value is an array indicates a group of
Chris@0 58 * options. The translated string is used as the label attribute for the
Chris@0 59 * optgroup. Do not use placeholders to sanitize data: doing so will lead
Chris@0 60 * to double-escaping. The array should contain the options you wish to
Chris@0 61 * group and should follow the syntax of $element['#options'].
Chris@0 62 * - If the function encounters a string or integer key whose value is an
Chris@0 63 * object with an 'option' property, the key is ignored, the contents of
Chris@0 64 * the option property are interpreted as $element['#options'], and the
Chris@0 65 * resulting HTML is added to the output.
Chris@0 66 * - #value: Optional integer, string, or array representing which option(s)
Chris@0 67 * to pre-select when the list is first displayed. The integer or string
Chris@0 68 * must match the key of an option in the '#options' list. If '#multiple' is
Chris@0 69 * TRUE, this can be an array of integers or strings.
Chris@0 70 * @param array|null $choices
Chris@0 71 * (optional) Either an associative array of options in the same format as
Chris@0 72 * $element['#options'] above, or NULL. This parameter is only used internally
Chris@0 73 * and is not intended to be passed in to the initial function call.
Chris@0 74 *
Chris@0 75 * @return mixed[]
Chris@0 76 * A structured, possibly nested, array of options and optgroups for use in a
Chris@0 77 * select form element.
Chris@0 78 * - label: A translated string whose value is the text of a single HTML
Chris@0 79 * option element, or the label attribute for an optgroup.
Chris@0 80 * - options: Optional, array of options for an optgroup.
Chris@0 81 * - selected: A boolean that indicates whether the option is selected when
Chris@0 82 * rendered.
Chris@0 83 * - type: A string that defines the element type. The value can be 'option'
Chris@0 84 * or 'optgroup'.
Chris@0 85 * - value: A string that contains the value attribute for the option.
Chris@0 86 */
Chris@0 87 function form_select_options($element, $choices = NULL) {
Chris@0 88 if (!isset($choices)) {
Chris@0 89 if (empty($element['#options'])) {
Chris@0 90 return [];
Chris@0 91 }
Chris@0 92 $choices = $element['#options'];
Chris@0 93 }
Chris@0 94 // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
Chris@0 95 // isset() fails in this situation.
Chris@0 96 $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
Chris@0 97 $value_is_array = $value_valid && is_array($element['#value']);
Chris@0 98 // Check if the element is multiple select and no value has been selected.
Chris@0 99 $empty_value = (empty($element['#value']) && !empty($element['#multiple']));
Chris@0 100 $options = [];
Chris@0 101 foreach ($choices as $key => $choice) {
Chris@0 102 if (is_array($choice)) {
Chris@0 103 $options[] = [
Chris@0 104 'type' => 'optgroup',
Chris@0 105 'label' => $key,
Chris@0 106 'options' => form_select_options($element, $choice),
Chris@0 107 ];
Chris@0 108 }
Chris@0 109 elseif (is_object($choice) && isset($choice->option)) {
Chris@0 110 $options = array_merge($options, form_select_options($element, $choice->option));
Chris@0 111 }
Chris@0 112 else {
Chris@0 113 $option = [];
Chris@0 114 $key = (string) $key;
Chris@0 115 $empty_choice = $empty_value && $key == '_none';
Chris@0 116 if ($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice)) {
Chris@0 117 $option['selected'] = TRUE;
Chris@0 118 }
Chris@0 119 else {
Chris@0 120 $option['selected'] = FALSE;
Chris@0 121 }
Chris@0 122 $option['type'] = 'option';
Chris@0 123 $option['value'] = $key;
Chris@0 124 $option['label'] = $choice;
Chris@0 125 $options[] = $option;
Chris@0 126 }
Chris@0 127 }
Chris@0 128 return $options;
Chris@0 129 }
Chris@0 130
Chris@0 131 /**
Chris@0 132 * Returns the indexes of a select element's options matching a given key.
Chris@0 133 *
Chris@0 134 * This function is useful if you need to modify the options that are
Chris@0 135 * already in a form element; for example, to remove choices which are
Chris@0 136 * not valid because of additional filters imposed by another module.
Chris@0 137 * One example might be altering the choices in a taxonomy selector.
Chris@0 138 * To correctly handle the case of a multiple hierarchy taxonomy,
Chris@0 139 * #options arrays can now hold an array of objects, instead of a
Chris@0 140 * direct mapping of keys to labels, so that multiple choices in the
Chris@0 141 * selector can have the same key (and label). This makes it difficult
Chris@0 142 * to manipulate directly, which is why this helper function exists.
Chris@0 143 *
Chris@0 144 * This function does not support optgroups (when the elements of the
Chris@0 145 * #options array are themselves arrays), and will return FALSE if
Chris@0 146 * arrays are found. The caller must either flatten/restore or
Chris@0 147 * manually do their manipulations in this case, since returning the
Chris@0 148 * index is not sufficient, and supporting this would make the
Chris@0 149 * "helper" too complicated and cumbersome to be of any help.
Chris@0 150 *
Chris@0 151 * As usual with functions that can return array() or FALSE, do not
Chris@0 152 * forget to use === and !== if needed.
Chris@0 153 *
Chris@0 154 * @param $element
Chris@0 155 * The select element to search.
Chris@0 156 * @param $key
Chris@0 157 * The key to look for.
Chris@0 158 *
Chris@0 159 * @return
Chris@0 160 * An array of indexes that match the given $key. Array will be
Chris@0 161 * empty if no elements were found. FALSE if optgroups were found.
Chris@0 162 */
Chris@0 163 function form_get_options($element, $key) {
Chris@0 164 $keys = [];
Chris@0 165 foreach ($element['#options'] as $index => $choice) {
Chris@0 166 if (is_array($choice)) {
Chris@0 167 return FALSE;
Chris@0 168 }
Chris@0 169 elseif (is_object($choice)) {
Chris@0 170 if (isset($choice->option[$key])) {
Chris@0 171 $keys[] = $index;
Chris@0 172 }
Chris@0 173 }
Chris@0 174 elseif ($index == $key) {
Chris@0 175 $keys[] = $index;
Chris@0 176 }
Chris@0 177 }
Chris@0 178 return $keys;
Chris@0 179 }
Chris@0 180
Chris@0 181 /**
Chris@0 182 * Prepares variables for fieldset element templates.
Chris@0 183 *
Chris@0 184 * Default template: fieldset.html.twig.
Chris@0 185 *
Chris@0 186 * @param array $variables
Chris@0 187 * An associative array containing:
Chris@0 188 * - element: An associative array containing the properties of the element.
Chris@0 189 * Properties used: #attributes, #children, #description, #id, #title,
Chris@0 190 * #value.
Chris@0 191 */
Chris@0 192 function template_preprocess_fieldset(&$variables) {
Chris@0 193 $element = $variables['element'];
Chris@0 194 Element::setAttributes($element, ['id']);
Chris@0 195 RenderElement::setAttributes($element);
Chris@0 196 $variables['attributes'] = isset($element['#attributes']) ? $element['#attributes'] : [];
Chris@0 197 $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
Chris@0 198 $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
Chris@0 199 $variables['title_display'] = isset($element['#title_display']) ? $element['#title_display'] : NULL;
Chris@0 200 $variables['children'] = $element['#children'];
Chris@0 201 $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
Chris@0 202
Chris@0 203 if (isset($element['#title']) && $element['#title'] !== '') {
Chris@0 204 $variables['legend']['title'] = ['#markup' => $element['#title']];
Chris@0 205 }
Chris@0 206
Chris@0 207 $variables['legend']['attributes'] = new Attribute();
Chris@0 208 // Add 'visually-hidden' class to legend span.
Chris@0 209 if ($variables['title_display'] == 'invisible') {
Chris@0 210 $variables['legend_span']['attributes'] = new Attribute(['class' => ['visually-hidden']]);
Chris@0 211 }
Chris@0 212 else {
Chris@0 213 $variables['legend_span']['attributes'] = new Attribute();
Chris@0 214 }
Chris@0 215
Chris@0 216 if (!empty($element['#description'])) {
Chris@0 217 $description_id = $element['#attributes']['id'] . '--description';
Chris@0 218 $description_attributes['id'] = $description_id;
Chris@0 219 $variables['description']['attributes'] = new Attribute($description_attributes);
Chris@0 220 $variables['description']['content'] = $element['#description'];
Chris@0 221
Chris@0 222 // Add the description's id to the fieldset aria attributes.
Chris@0 223 $variables['attributes']['aria-describedby'] = $description_id;
Chris@0 224 }
Chris@0 225
Chris@0 226 // Suppress error messages.
Chris@0 227 $variables['errors'] = NULL;
Chris@0 228 }
Chris@0 229
Chris@0 230 /**
Chris@0 231 * Prepares variables for details element templates.
Chris@0 232 *
Chris@0 233 * Default template: details.html.twig.
Chris@0 234 *
Chris@0 235 * @param array $variables
Chris@0 236 * An associative array containing:
Chris@0 237 * - element: An associative array containing the properties of the element.
Chris@17 238 * Properties used: #attributes, #children, #description, #required,
Chris@17 239 * #summary_attributes, #title, #value.
Chris@0 240 */
Chris@0 241 function template_preprocess_details(&$variables) {
Chris@0 242 $element = $variables['element'];
Chris@0 243 $variables['attributes'] = $element['#attributes'];
Chris@17 244 $variables['summary_attributes'] = new Attribute($element['#summary_attributes']);
Chris@0 245 if (!empty($element['#title'])) {
Chris@0 246 $variables['summary_attributes']['role'] = 'button';
Chris@0 247 if (!empty($element['#attributes']['id'])) {
Chris@0 248 $variables['summary_attributes']['aria-controls'] = $element['#attributes']['id'];
Chris@0 249 }
Chris@0 250 $variables['summary_attributes']['aria-expanded'] = !empty($element['#attributes']['open']) ? 'true' : 'false';
Chris@0 251 $variables['summary_attributes']['aria-pressed'] = $variables['summary_attributes']['aria-expanded'];
Chris@0 252 }
Chris@0 253 $variables['title'] = (!empty($element['#title'])) ? $element['#title'] : '';
Chris@17 254 // If the element title is a string, wrap it a render array so that markup
Chris@17 255 // will not be escaped (but XSS-filtered).
Chris@17 256 if (is_string($variables['title']) && $variables['title'] !== '') {
Chris@17 257 $variables['title'] = ['#markup' => $variables['title']];
Chris@17 258 }
Chris@0 259 $variables['description'] = (!empty($element['#description'])) ? $element['#description'] : '';
Chris@0 260 $variables['children'] = (isset($element['#children'])) ? $element['#children'] : '';
Chris@0 261 $variables['value'] = (isset($element['#value'])) ? $element['#value'] : '';
Chris@0 262 $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
Chris@0 263
Chris@0 264 // Suppress error messages.
Chris@0 265 $variables['errors'] = NULL;
Chris@0 266 }
Chris@0 267
Chris@0 268 /**
Chris@0 269 * Prepares variables for radios templates.
Chris@0 270 *
Chris@0 271 * Default template: radios.html.twig.
Chris@0 272 *
Chris@0 273 * @param array $variables
Chris@0 274 * An associative array containing:
Chris@0 275 * - element: An associative array containing the properties of the element.
Chris@0 276 * Properties used: #title, #value, #options, #description, #required,
Chris@0 277 * #attributes, #children.
Chris@0 278 */
Chris@0 279 function template_preprocess_radios(&$variables) {
Chris@0 280 $element = $variables['element'];
Chris@0 281 $variables['attributes'] = [];
Chris@0 282 if (isset($element['#id'])) {
Chris@0 283 $variables['attributes']['id'] = $element['#id'];
Chris@0 284 }
Chris@0 285 if (isset($element['#attributes']['title'])) {
Chris@0 286 $variables['attributes']['title'] = $element['#attributes']['title'];
Chris@0 287 }
Chris@0 288 $variables['children'] = $element['#children'];
Chris@0 289 }
Chris@0 290
Chris@0 291 /**
Chris@0 292 * Prepares variables for checkboxes templates.
Chris@0 293 *
Chris@0 294 * Default template: checkboxes.html.twig.
Chris@0 295 *
Chris@0 296 * @param array $variables
Chris@0 297 * An associative array containing:
Chris@0 298 * - element: An associative array containing the properties of the element.
Chris@0 299 * Properties used: #children, #attributes.
Chris@0 300 */
Chris@0 301 function template_preprocess_checkboxes(&$variables) {
Chris@0 302 $element = $variables['element'];
Chris@0 303 $variables['attributes'] = [];
Chris@0 304 if (isset($element['#id'])) {
Chris@0 305 $variables['attributes']['id'] = $element['#id'];
Chris@0 306 }
Chris@0 307 if (isset($element['#attributes']['title'])) {
Chris@0 308 $variables['attributes']['title'] = $element['#attributes']['title'];
Chris@0 309 }
Chris@0 310 $variables['children'] = $element['#children'];
Chris@0 311 }
Chris@0 312
Chris@0 313 /**
Chris@0 314 * Prepares variables for vertical tabs templates.
Chris@0 315 *
Chris@0 316 * Default template: vertical-tabs.html.twig.
Chris@0 317 *
Chris@0 318 * @param array $variables
Chris@0 319 * An associative array containing:
Chris@0 320 * - element: An associative array containing the properties and children of
Chris@0 321 * the details element. Properties used: #children.
Chris@0 322 */
Chris@0 323 function template_preprocess_vertical_tabs(&$variables) {
Chris@0 324 $element = $variables['element'];
Chris@0 325 $variables['children'] = (!empty($element['#children'])) ? $element['#children'] : '';
Chris@0 326 }
Chris@0 327
Chris@0 328 /**
Chris@0 329 * Prepares variables for input templates.
Chris@0 330 *
Chris@0 331 * Default template: input.html.twig.
Chris@0 332 *
Chris@0 333 * @param array $variables
Chris@0 334 * An associative array containing:
Chris@0 335 * - element: An associative array containing the properties of the element.
Chris@0 336 * Properties used: #attributes.
Chris@0 337 */
Chris@0 338 function template_preprocess_input(&$variables) {
Chris@0 339 $element = $variables['element'];
Chris@0 340 // Remove name attribute if empty, for W3C compliance.
Chris@0 341 if (isset($variables['attributes']['name']) && empty((string) $variables['attributes']['name'])) {
Chris@0 342 unset($variables['attributes']['name']);
Chris@0 343 }
Chris@0 344 $variables['children'] = $element['#children'];
Chris@0 345 }
Chris@0 346
Chris@0 347 /**
Chris@0 348 * Prepares variables for form templates.
Chris@0 349 *
Chris@0 350 * Default template: form.html.twig.
Chris@0 351 *
Chris@0 352 * @param $variables
Chris@0 353 * An associative array containing:
Chris@0 354 * - element: An associative array containing the properties of the element.
Chris@0 355 * Properties used: #action, #method, #attributes, #children
Chris@0 356 */
Chris@0 357 function template_preprocess_form(&$variables) {
Chris@0 358 $element = $variables['element'];
Chris@0 359 if (isset($element['#action'])) {
Chris@0 360 $element['#attributes']['action'] = UrlHelper::stripDangerousProtocols($element['#action']);
Chris@0 361 }
Chris@0 362 Element::setAttributes($element, ['method', 'id']);
Chris@0 363 if (empty($element['#attributes']['accept-charset'])) {
Chris@0 364 $element['#attributes']['accept-charset'] = "UTF-8";
Chris@0 365 }
Chris@0 366 $variables['attributes'] = $element['#attributes'];
Chris@0 367 $variables['children'] = $element['#children'];
Chris@0 368 }
Chris@0 369
Chris@0 370 /**
Chris@0 371 * Prepares variables for textarea templates.
Chris@0 372 *
Chris@0 373 * Default template: textarea.html.twig.
Chris@0 374 *
Chris@0 375 * @param array $variables
Chris@0 376 * An associative array containing:
Chris@0 377 * - element: An associative array containing the properties of the element.
Chris@0 378 * Properties used: #title, #value, #description, #rows, #cols, #maxlength,
Chris@0 379 * #placeholder, #required, #attributes, #resizable.
Chris@0 380 */
Chris@0 381 function template_preprocess_textarea(&$variables) {
Chris@0 382 $element = $variables['element'];
Chris@0 383 $attributes = ['id', 'name', 'rows', 'cols', 'maxlength', 'placeholder'];
Chris@0 384 Element::setAttributes($element, $attributes);
Chris@0 385 RenderElement::setAttributes($element, ['form-textarea']);
Chris@0 386 $variables['wrapper_attributes'] = new Attribute();
Chris@0 387 $variables['attributes'] = new Attribute($element['#attributes']);
Chris@0 388 $variables['value'] = $element['#value'];
Chris@0 389 $variables['resizable'] = !empty($element['#resizable']) ? $element['#resizable'] : NULL;
Chris@0 390 $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
Chris@0 391 }
Chris@0 392
Chris@0 393 /**
Chris@0 394 * Returns HTML for a form element.
Chris@0 395 * Prepares variables for form element templates.
Chris@0 396 *
Chris@0 397 * Default template: form-element.html.twig.
Chris@0 398 *
Chris@0 399 * In addition to the element itself, the DIV contains a label for the element
Chris@0 400 * based on the optional #title_display property, and an optional #description.
Chris@0 401 *
Chris@0 402 * The optional #title_display property can have these values:
Chris@0 403 * - before: The label is output before the element. This is the default.
Chris@0 404 * The label includes the #title and the required marker, if #required.
Chris@0 405 * - after: The label is output after the element. For example, this is used
Chris@0 406 * for radio and checkbox #type elements. If the #title is empty but the field
Chris@0 407 * is #required, the label will contain only the required marker.
Chris@0 408 * - invisible: Labels are critical for screen readers to enable them to
Chris@0 409 * properly navigate through forms but can be visually distracting. This
Chris@0 410 * property hides the label for everyone except screen readers.
Chris@0 411 * - attribute: Set the title attribute on the element to create a tooltip
Chris@0 412 * but output no label element. This is supported only for checkboxes
Chris@0 413 * and radios in
Chris@0 414 * \Drupal\Core\Render\Element\CompositeFormElementTrait::preRenderCompositeFormElement().
Chris@0 415 * It is used where a visual label is not needed, such as a table of
Chris@0 416 * checkboxes where the row and column provide the context. The tooltip will
Chris@0 417 * include the title and required marker.
Chris@0 418 *
Chris@0 419 * If the #title property is not set, then the label and any required marker
Chris@0 420 * will not be output, regardless of the #title_display or #required values.
Chris@0 421 * This can be useful in cases such as the password_confirm element, which
Chris@0 422 * creates children elements that have their own labels and required markers,
Chris@0 423 * but the parent element should have neither. Use this carefully because a
Chris@0 424 * field without an associated label can cause accessibility challenges.
Chris@0 425 *
Chris@18 426 * To associate the label with a different field, set the #label_for property
Chris@18 427 * to the ID of the desired field.
Chris@18 428 *
Chris@0 429 * @param array $variables
Chris@0 430 * An associative array containing:
Chris@0 431 * - element: An associative array containing the properties of the element.
Chris@0 432 * Properties used: #title, #title_display, #description, #id, #required,
Chris@18 433 * #children, #type, #name, #label_for.
Chris@0 434 */
Chris@0 435 function template_preprocess_form_element(&$variables) {
Chris@0 436 $element = &$variables['element'];
Chris@0 437
Chris@0 438 // This function is invoked as theme wrapper, but the rendered form element
Chris@0 439 // may not necessarily have been processed by
Chris@0 440 // \Drupal::formBuilder()->doBuildForm().
Chris@0 441 $element += [
Chris@0 442 '#title_display' => 'before',
Chris@0 443 '#wrapper_attributes' => [],
Chris@0 444 '#label_attributes' => [],
Chris@18 445 '#label_for' => NULL,
Chris@0 446 ];
Chris@0 447 $variables['attributes'] = $element['#wrapper_attributes'];
Chris@0 448
Chris@0 449 // Add element #id for #type 'item'.
Chris@0 450 if (isset($element['#markup']) && !empty($element['#id'])) {
Chris@0 451 $variables['attributes']['id'] = $element['#id'];
Chris@0 452 }
Chris@0 453
Chris@0 454 // Pass elements #type and #name to template.
Chris@0 455 if (!empty($element['#type'])) {
Chris@0 456 $variables['type'] = $element['#type'];
Chris@0 457 }
Chris@0 458 if (!empty($element['#name'])) {
Chris@0 459 $variables['name'] = $element['#name'];
Chris@0 460 }
Chris@0 461
Chris@0 462 // Pass elements disabled status to template.
Chris@0 463 $variables['disabled'] = !empty($element['#attributes']['disabled']) ? $element['#attributes']['disabled'] : NULL;
Chris@0 464
Chris@0 465 // Suppress error messages.
Chris@0 466 $variables['errors'] = NULL;
Chris@0 467
Chris@0 468 // If #title is not set, we don't display any label.
Chris@0 469 if (!isset($element['#title'])) {
Chris@0 470 $element['#title_display'] = 'none';
Chris@0 471 }
Chris@0 472
Chris@0 473 $variables['title_display'] = $element['#title_display'];
Chris@0 474
Chris@0 475 $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
Chris@0 476 $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
Chris@0 477
Chris@0 478 $variables['description'] = NULL;
Chris@0 479 if (!empty($element['#description'])) {
Chris@0 480 $variables['description_display'] = $element['#description_display'];
Chris@0 481 $description_attributes = [];
Chris@0 482 if (!empty($element['#id'])) {
Chris@0 483 $description_attributes['id'] = $element['#id'] . '--description';
Chris@0 484 }
Chris@0 485 $variables['description']['attributes'] = new Attribute($description_attributes);
Chris@0 486 $variables['description']['content'] = $element['#description'];
Chris@0 487 }
Chris@0 488
Chris@0 489 // Add label_display and label variables to template.
Chris@0 490 $variables['label_display'] = $element['#title_display'];
Chris@0 491 $variables['label'] = ['#theme' => 'form_element_label'];
Chris@0 492 $variables['label'] += array_intersect_key($element, array_flip(['#id', '#required', '#title', '#title_display']));
Chris@0 493 $variables['label']['#attributes'] = $element['#label_attributes'];
Chris@18 494 if (!empty($element['#label_for'])) {
Chris@18 495 $variables['label']['#for'] = $element['#label_for'];
Chris@18 496 if (!empty($element['#id'])) {
Chris@18 497 $variables['label']['#id'] = $element['#id'] . '--label';
Chris@18 498 }
Chris@18 499 }
Chris@0 500
Chris@0 501 $variables['children'] = $element['#children'];
Chris@0 502 }
Chris@0 503
Chris@0 504 /**
Chris@0 505 * Prepares variables for form label templates.
Chris@0 506 *
Chris@0 507 * Form element labels include the #title and a #required marker. The label is
Chris@0 508 * associated with the element itself by the element #id. Labels may appear
Chris@0 509 * before or after elements, depending on form-element.html.twig and
Chris@0 510 * #title_display.
Chris@0 511 *
Chris@0 512 * This function will not be called for elements with no labels, depending on
Chris@0 513 * #title_display. For elements that have an empty #title and are not required,
Chris@0 514 * this function will output no label (''). For required elements that have an
Chris@0 515 * empty #title, this will output the required marker alone within the label.
Chris@0 516 * The label will use the #id to associate the marker with the field that is
Chris@0 517 * required. That is especially important for screenreader users to know
Chris@0 518 * which field is required.
Chris@0 519 *
Chris@18 520 * To associate the label with a different field, set the #for property to the
Chris@18 521 * ID of the desired field.
Chris@18 522 *
Chris@0 523 * @param array $variables
Chris@0 524 * An associative array containing:
Chris@0 525 * - element: An associative array containing the properties of the element.
Chris@18 526 * Properties used: #required, #title, #id, #value, #description, #for.
Chris@0 527 */
Chris@0 528 function template_preprocess_form_element_label(&$variables) {
Chris@0 529 $element = $variables['element'];
Chris@0 530 // If title and required marker are both empty, output no label.
Chris@0 531 if (isset($element['#title']) && $element['#title'] !== '') {
Chris@0 532 $variables['title'] = ['#markup' => $element['#title']];
Chris@0 533 }
Chris@0 534
Chris@0 535 // Pass elements title_display to template.
Chris@0 536 $variables['title_display'] = $element['#title_display'];
Chris@0 537
Chris@0 538 // A #for property of a dedicated #type 'label' element as precedence.
Chris@0 539 if (!empty($element['#for'])) {
Chris@0 540 $variables['attributes']['for'] = $element['#for'];
Chris@0 541 // A custom #id allows the referenced form input element to refer back to
Chris@0 542 // the label element; e.g., in the 'aria-labelledby' attribute.
Chris@0 543 if (!empty($element['#id'])) {
Chris@0 544 $variables['attributes']['id'] = $element['#id'];
Chris@0 545 }
Chris@0 546 }
Chris@0 547 // Otherwise, point to the #id of the form input element.
Chris@0 548 elseif (!empty($element['#id'])) {
Chris@0 549 $variables['attributes']['for'] = $element['#id'];
Chris@0 550 }
Chris@0 551
Chris@0 552 // Pass elements required to template.
Chris@0 553 $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
Chris@0 554 }
Chris@0 555
Chris@0 556 /**
Chris@0 557 * @defgroup batch Batch operations
Chris@0 558 * @{
Chris@0 559 * Creates and processes batch operations.
Chris@0 560 *
Chris@0 561 * Functions allowing forms processing to be spread out over several page
Chris@0 562 * requests, thus ensuring that the processing does not get interrupted
Chris@0 563 * because of a PHP timeout, while allowing the user to receive feedback
Chris@0 564 * on the progress of the ongoing operations.
Chris@0 565 *
Chris@0 566 * The API is primarily designed to integrate nicely with the Form API
Chris@0 567 * workflow, but can also be used by non-Form API scripts (like update.php)
Chris@0 568 * or even simple page callbacks (which should probably be used sparingly).
Chris@0 569 *
Chris@0 570 * Example:
Chris@0 571 * @code
Chris@0 572 * $batch = array(
Chris@0 573 * 'title' => t('Exporting'),
Chris@0 574 * 'operations' => array(
Chris@0 575 * array('my_function_1', array($account->id(), 'story')),
Chris@0 576 * array('my_function_2', array()),
Chris@0 577 * ),
Chris@0 578 * 'finished' => 'my_finished_callback',
Chris@0 579 * 'file' => 'path_to_file_containing_myfunctions',
Chris@0 580 * );
Chris@0 581 * batch_set($batch);
Chris@0 582 * // Only needed if not inside a form _submit handler.
Chris@0 583 * // Setting redirect in batch_process.
Chris@0 584 * batch_process('node/1');
Chris@0 585 * @endcode
Chris@0 586 *
Chris@0 587 * Note: if the batch 'title', 'init_message', 'progress_message', or
Chris@0 588 * 'error_message' could contain any user input, it is the responsibility of
Chris@0 589 * the code calling batch_set() to sanitize them first with a function like
Chris@0 590 * \Drupal\Component\Utility\Html::escape() or
Chris@0 591 * \Drupal\Component\Utility\Xss::filter(). Furthermore, if the batch operation
Chris@0 592 * returns any user input in the 'results' or 'message' keys of $context, it
Chris@0 593 * must also sanitize them first.
Chris@0 594 *
Chris@0 595 * Sample callback_batch_operation():
Chris@0 596 * @code
Chris@0 597 * // Simple and artificial: load a node of a given type for a given user
Chris@0 598 * function my_function_1($uid, $type, &$context) {
Chris@0 599 * // The $context array gathers batch context information about the execution (read),
Chris@0 600 * // as well as 'return values' for the current operation (write)
Chris@0 601 * // The following keys are provided :
Chris@0 602 * // 'results' (read / write): The array of results gathered so far by
Chris@0 603 * // the batch processing, for the current operation to append its own.
Chris@0 604 * // 'message' (write): A text message displayed in the progress page.
Chris@0 605 * // The following keys allow for multi-step operations :
Chris@0 606 * // 'sandbox' (read / write): An array that can be freely used to
Chris@0 607 * // store persistent data between iterations. It is recommended to
Chris@0 608 * // use this instead of $_SESSION, which is unsafe if the user
Chris@0 609 * // continues browsing in a separate window while the batch is processing.
Chris@0 610 * // 'finished' (write): A float number between 0 and 1 informing
Chris@0 611 * // the processing engine of the completion level for the operation.
Chris@0 612 * // 1 (or no value explicitly set) means the operation is finished
Chris@0 613 * // and the batch processing can continue to the next operation.
Chris@0 614 *
Chris@0 615 * $nodes = \Drupal::entityTypeManager()->getStorage('node')
Chris@0 616 * ->loadByProperties(['uid' => $uid, 'type' => $type]);
Chris@0 617 * $node = reset($nodes);
Chris@0 618 * $context['results'][] = $node->id() . ' : ' . Html::escape($node->label());
Chris@0 619 * $context['message'] = Html::escape($node->label());
Chris@0 620 * }
Chris@0 621 *
Chris@0 622 * // A more advanced example is a multi-step operation that loads all rows,
Chris@0 623 * // five by five.
Chris@0 624 * function my_function_2(&$context) {
Chris@0 625 * if (empty($context['sandbox'])) {
Chris@0 626 * $context['sandbox']['progress'] = 0;
Chris@0 627 * $context['sandbox']['current_id'] = 0;
Chris@0 628 * $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT id) FROM {example}')->fetchField();
Chris@0 629 * }
Chris@0 630 * $limit = 5;
Chris@0 631 * $result = db_select('example')
Chris@0 632 * ->fields('example', array('id'))
Chris@0 633 * ->condition('id', $context['sandbox']['current_id'], '>')
Chris@0 634 * ->orderBy('id')
Chris@0 635 * ->range(0, $limit)
Chris@0 636 * ->execute();
Chris@0 637 * foreach ($result as $row) {
Chris@0 638 * $context['results'][] = $row->id . ' : ' . Html::escape($row->title);
Chris@0 639 * $context['sandbox']['progress']++;
Chris@0 640 * $context['sandbox']['current_id'] = $row->id;
Chris@0 641 * $context['message'] = Html::escape($row->title);
Chris@0 642 * }
Chris@0 643 * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
Chris@0 644 * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
Chris@0 645 * }
Chris@0 646 * }
Chris@0 647 * @endcode
Chris@0 648 *
Chris@0 649 * Sample callback_batch_finished():
Chris@0 650 * @code
Chris@0 651 * function my_finished_callback($success, $results, $operations) {
Chris@0 652 * // The 'success' parameter means no fatal PHP errors were detected. All
Chris@0 653 * // other error management should be handled using 'results'.
Chris@0 654 * if ($success) {
Chris@0 655 * $message = \Drupal::translation()->formatPlural(count($results), 'One post processed.', '@count posts processed.');
Chris@0 656 * }
Chris@0 657 * else {
Chris@0 658 * $message = t('Finished with an error.');
Chris@0 659 * }
Chris@17 660 * \Drupal::messenger()->addMessage($message);
Chris@0 661 * // Providing data for the redirected page is done through $_SESSION.
Chris@0 662 * foreach ($results as $result) {
Chris@0 663 * $items[] = t('Loaded node %title.', array('%title' => $result));
Chris@0 664 * }
Chris@0 665 * $_SESSION['my_batch_results'] = $items;
Chris@0 666 * }
Chris@0 667 * @endcode
Chris@0 668 */
Chris@0 669
Chris@0 670 /**
Chris@0 671 * Adds a new batch.
Chris@0 672 *
Chris@0 673 * Batch operations are added as new batch sets. Batch sets are used to spread
Chris@0 674 * processing (primarily, but not exclusively, forms processing) over several
Chris@0 675 * page requests. This helps to ensure that the processing is not interrupted
Chris@0 676 * due to PHP timeouts, while users are still able to receive feedback on the
Chris@0 677 * progress of the ongoing operations. Combining related operations into
Chris@0 678 * distinct batch sets provides clean code independence for each batch set,
Chris@0 679 * ensuring that two or more batches, submitted independently, can be processed
Chris@0 680 * without mutual interference. Each batch set may specify its own set of
Chris@0 681 * operations and results, produce its own UI messages, and trigger its own
Chris@0 682 * 'finished' callback. Batch sets are processed sequentially, with the progress
Chris@0 683 * bar starting afresh for each new set.
Chris@0 684 *
Chris@0 685 * @param $batch_definition
Chris@0 686 * An associative array defining the batch, with the following elements (all
Chris@0 687 * are optional except as noted):
Chris@0 688 * - operations: (required) Array of operations to be performed, where each
Chris@0 689 * item is an array consisting of the name of an implementation of
Chris@0 690 * callback_batch_operation() and an array of parameter.
Chris@0 691 * Example:
Chris@0 692 * @code
Chris@0 693 * array(
Chris@0 694 * array('callback_batch_operation_1', array($arg1)),
Chris@0 695 * array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
Chris@0 696 * )
Chris@0 697 * @endcode
Chris@0 698 * - title: A safe, translated string to use as the title for the progress
Chris@0 699 * page. Defaults to t('Processing').
Chris@0 700 * - init_message: Message displayed while the processing is initialized.
Chris@0 701 * Defaults to t('Initializing.').
Chris@0 702 * - progress_message: Message displayed while processing the batch. Available
Chris@0 703 * placeholders are @current, @remaining, @total, @percentage, @estimate and
Chris@0 704 * @elapsed. Defaults to t('Completed @current of @total.').
Chris@0 705 * - error_message: Message displayed if an error occurred while processing
Chris@0 706 * the batch. Defaults to t('An error has occurred.').
Chris@0 707 * - finished: Name of an implementation of callback_batch_finished(). This is
Chris@0 708 * executed after the batch has completed. This should be used to perform
Chris@0 709 * any result massaging that may be needed, and possibly save data in
Chris@0 710 * $_SESSION for display after final page redirection.
Chris@0 711 * - file: Path to the file containing the definitions of the 'operations' and
Chris@0 712 * 'finished' functions, for instance if they don't reside in the main
Chris@0 713 * .module file. The path should be relative to base_path(), and thus should
Chris@0 714 * be built using drupal_get_path().
Chris@0 715 * - library: An array of batch-specific CSS and JS libraries.
Chris@0 716 * - url_options: options passed to the \Drupal\Core\Url object when
Chris@0 717 * constructing redirect URLs for the batch.
Chris@0 718 * - progressive: A Boolean that indicates whether or not the batch needs to
Chris@0 719 * run progressively. TRUE indicates that the batch will run in more than
Chris@0 720 * one run. FALSE (default) indicates that the batch will finish in a single
Chris@0 721 * run.
Chris@0 722 * - queue: An override of the default queue (with name and class fields
Chris@0 723 * optional). An array containing two elements:
Chris@0 724 * - name: Unique identifier for the queue.
Chris@0 725 * - class: The name of a class that implements
Chris@0 726 * \Drupal\Core\Queue\QueueInterface, including the full namespace but not
Chris@0 727 * starting with a backslash. It must have a constructor with two
Chris@0 728 * arguments: $name and a \Drupal\Core\Database\Connection object.
Chris@0 729 * Typically, the class will either be \Drupal\Core\Queue\Batch or
Chris@0 730 * \Drupal\Core\Queue\BatchMemory. Defaults to Batch if progressive is
Chris@0 731 * TRUE, or to BatchMemory if progressive is FALSE.
Chris@0 732 */
Chris@0 733 function batch_set($batch_definition) {
Chris@0 734 if ($batch_definition) {
Chris@0 735 $batch =& batch_get();
Chris@0 736
Chris@0 737 // Initialize the batch if needed.
Chris@0 738 if (empty($batch)) {
Chris@0 739 $batch = [
Chris@0 740 'sets' => [],
Chris@0 741 'has_form_submits' => FALSE,
Chris@0 742 ];
Chris@0 743 }
Chris@0 744
Chris@0 745 // Base and default properties for the batch set.
Chris@0 746 $init = [
Chris@0 747 'sandbox' => [],
Chris@0 748 'results' => [],
Chris@0 749 'success' => FALSE,
Chris@0 750 'start' => 0,
Chris@0 751 'elapsed' => 0,
Chris@0 752 ];
Chris@0 753 $defaults = [
Chris@0 754 'title' => t('Processing'),
Chris@0 755 'init_message' => t('Initializing.'),
Chris@0 756 'progress_message' => t('Completed @current of @total.'),
Chris@0 757 'error_message' => t('An error has occurred.'),
Chris@0 758 ];
Chris@0 759 $batch_set = $init + $batch_definition + $defaults;
Chris@0 760
Chris@0 761 // Tweak init_message to avoid the bottom of the page flickering down after
Chris@0 762 // init phase.
Chris@0 763 $batch_set['init_message'] .= '<br/>&nbsp;';
Chris@0 764
Chris@0 765 // The non-concurrent workflow of batch execution allows us to save
Chris@0 766 // numberOfItems() queries by handling our own counter.
Chris@0 767 $batch_set['total'] = count($batch_set['operations']);
Chris@0 768 $batch_set['count'] = $batch_set['total'];
Chris@0 769
Chris@0 770 // Add the set to the batch.
Chris@0 771 if (empty($batch['id'])) {
Chris@0 772 // The batch is not running yet. Simply add the new set.
Chris@0 773 $batch['sets'][] = $batch_set;
Chris@0 774 }
Chris@0 775 else {
Chris@0 776 // The set is being added while the batch is running. Insert the new set
Chris@0 777 // right after the current one to ensure execution order, and store its
Chris@0 778 // operations in a queue.
Chris@0 779 $index = $batch['current_set'] + 1;
Chris@0 780 $slice1 = array_slice($batch['sets'], 0, $index);
Chris@0 781 $slice2 = array_slice($batch['sets'], $index);
Chris@0 782 $batch['sets'] = array_merge($slice1, [$batch_set], $slice2);
Chris@0 783 _batch_populate_queue($batch, $index);
Chris@0 784 }
Chris@0 785 }
Chris@0 786 }
Chris@0 787
Chris@0 788 /**
Chris@0 789 * Processes the batch.
Chris@0 790 *
Chris@0 791 * This function is generally not needed in form submit handlers;
Chris@0 792 * Form API takes care of batches that were set during form submission.
Chris@0 793 *
Chris@0 794 * @param \Drupal\Core\Url|string $redirect
Chris@17 795 * (optional) Either a path or Url object to redirect to when the batch has
Chris@17 796 * finished processing. For example, to redirect users to the home page, use
Chris@17 797 * '<front>'. If you wish to allow standard form API batch handling to occur
Chris@17 798 * and force the user to be redirected to a custom location after the batch
Chris@17 799 * has finished processing, you do not need to use batch_process() and this
Chris@17 800 * parameter. Instead, make the batch 'finished' callback return an instance
Chris@17 801 * of \Symfony\Component\HttpFoundation\RedirectResponse, which will be used
Chris@0 802 * automatically by the standard batch processing pipeline (and which takes
Chris@17 803 * precedence over this parameter). If this parameter is omitted and no
Chris@17 804 * redirect response was returned by the 'finished' callback, the user will
Chris@17 805 * be redirected to the page that started the batch. Any query arguments will
Chris@17 806 * be automatically persisted.
Chris@0 807 * @param \Drupal\Core\Url $url
Chris@0 808 * (optional) URL of the batch processing page. Should only be used for
Chris@0 809 * separate scripts like update.php.
Chris@0 810 * @param $redirect_callback
Chris@0 811 * (optional) Specify a function to be called to redirect to the progressive
Chris@0 812 * processing page.
Chris@0 813 *
Chris@0 814 * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
Chris@0 815 * A redirect response if the batch is progressive. No return value otherwise.
Chris@0 816 */
Chris@0 817 function batch_process($redirect = NULL, Url $url = NULL, $redirect_callback = NULL) {
Chris@0 818 $batch =& batch_get();
Chris@0 819
Chris@0 820 if (isset($batch)) {
Chris@0 821 // Add process information
Chris@0 822 $process_info = [
Chris@0 823 'current_set' => 0,
Chris@0 824 'progressive' => TRUE,
Chris@0 825 'url' => isset($url) ? $url : Url::fromRoute('system.batch_page.html'),
Chris@0 826 'source_url' => Url::fromRouteMatch(\Drupal::routeMatch())->mergeOptions(['query' => \Drupal::request()->query->all()]),
Chris@0 827 'batch_redirect' => $redirect,
Chris@0 828 'theme' => \Drupal::theme()->getActiveTheme()->getName(),
Chris@0 829 'redirect_callback' => $redirect_callback,
Chris@0 830 ];
Chris@0 831 $batch += $process_info;
Chris@0 832
Chris@0 833 // The batch is now completely built. Allow other modules to make changes
Chris@0 834 // to the batch so that it is easier to reuse batch processes in other
Chris@0 835 // environments.
Chris@0 836 \Drupal::moduleHandler()->alter('batch', $batch);
Chris@0 837
Chris@0 838 // Assign an arbitrary id: don't rely on a serial column in the 'batch'
Chris@0 839 // table, since non-progressive batches skip database storage completely.
Chris@18 840 $batch['id'] = \Drupal::database()->nextId();
Chris@0 841
Chris@0 842 // Move operations to a job queue. Non-progressive batches will use a
Chris@0 843 // memory-based queue.
Chris@0 844 foreach ($batch['sets'] as $key => $batch_set) {
Chris@0 845 _batch_populate_queue($batch, $key);
Chris@0 846 }
Chris@0 847
Chris@0 848 // Initiate processing.
Chris@0 849 if ($batch['progressive']) {
Chris@0 850 // Now that we have a batch id, we can generate the redirection link in
Chris@0 851 // the generic error message.
Chris@0 852 /** @var \Drupal\Core\Url $batch_url */
Chris@0 853 $batch_url = $batch['url'];
Chris@0 854 /** @var \Drupal\Core\Url $error_url */
Chris@0 855 $error_url = clone $batch_url;
Chris@0 856 $query_options = $error_url->getOption('query');
Chris@0 857 $query_options['id'] = $batch['id'];
Chris@0 858 $query_options['op'] = 'finished';
Chris@0 859 $error_url->setOption('query', $query_options);
Chris@0 860
Chris@0 861 $batch['error_message'] = t('Please continue to <a href=":error_url">the error page</a>', [':error_url' => $error_url->toString(TRUE)->getGeneratedUrl()]);
Chris@0 862
Chris@0 863 // Clear the way for the redirection to the batch processing page, by
Chris@0 864 // saving and unsetting the 'destination', if there is any.
Chris@0 865 $request = \Drupal::request();
Chris@0 866 if ($request->query->has('destination')) {
Chris@0 867 $batch['destination'] = $request->query->get('destination');
Chris@0 868 $request->query->remove('destination');
Chris@0 869 }
Chris@0 870
Chris@0 871 // Store the batch.
Chris@0 872 \Drupal::service('batch.storage')->create($batch);
Chris@0 873
Chris@0 874 // Set the batch number in the session to guarantee that it will stay alive.
Chris@0 875 $_SESSION['batches'][$batch['id']] = TRUE;
Chris@0 876
Chris@0 877 // Redirect for processing.
Chris@0 878 $query_options = $error_url->getOption('query');
Chris@0 879 $query_options['op'] = 'start';
Chris@0 880 $query_options['id'] = $batch['id'];
Chris@0 881 $batch_url->setOption('query', $query_options);
Chris@0 882 if (($function = $batch['redirect_callback']) && function_exists($function)) {
Chris@0 883 $function($batch_url->toString(), ['query' => $query_options]);
Chris@0 884 }
Chris@0 885 else {
Chris@0 886 return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
Chris@0 887 }
Chris@0 888 }
Chris@0 889 else {
Chris@0 890 // Non-progressive execution: bypass the whole progressbar workflow
Chris@0 891 // and execute the batch in one pass.
Chris@0 892 require_once __DIR__ . '/batch.inc';
Chris@0 893 _batch_process();
Chris@0 894 }
Chris@0 895 }
Chris@0 896 }
Chris@0 897
Chris@0 898 /**
Chris@0 899 * Retrieves the current batch.
Chris@0 900 */
Chris@0 901 function &batch_get() {
Chris@0 902 // Not drupal_static(), because Batch API operates at a lower level than most
Chris@0 903 // use-cases for resetting static variables, and we specifically do not want a
Chris@0 904 // global drupal_static_reset() resetting the batch information. Functions
Chris@0 905 // that are part of the Batch API and need to reset the batch information may
Chris@0 906 // call batch_get() and manipulate the result by reference. Functions that are
Chris@0 907 // not part of the Batch API can also do this, but shouldn't.
Chris@0 908 static $batch = [];
Chris@0 909 return $batch;
Chris@0 910 }
Chris@0 911
Chris@0 912 /**
Chris@0 913 * Populates a job queue with the operations of a batch set.
Chris@0 914 *
Chris@0 915 * Depending on whether the batch is progressive or not, the
Chris@0 916 * Drupal\Core\Queue\Batch or Drupal\Core\Queue\BatchMemory handler classes will
Chris@0 917 * be used. The name and class of the queue are added by reference to the
Chris@0 918 * batch set.
Chris@0 919 *
Chris@0 920 * @param $batch
Chris@0 921 * The batch array.
Chris@0 922 * @param $set_id
Chris@0 923 * The id of the set to process.
Chris@0 924 */
Chris@0 925 function _batch_populate_queue(&$batch, $set_id) {
Chris@0 926 $batch_set = &$batch['sets'][$set_id];
Chris@0 927
Chris@0 928 if (isset($batch_set['operations'])) {
Chris@0 929 $batch_set += [
Chris@0 930 'queue' => [
Chris@0 931 'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
Chris@0 932 'class' => $batch['progressive'] ? 'Drupal\Core\Queue\Batch' : 'Drupal\Core\Queue\BatchMemory',
Chris@0 933 ],
Chris@0 934 ];
Chris@0 935
Chris@0 936 $queue = _batch_queue($batch_set);
Chris@0 937 $queue->createQueue();
Chris@0 938 foreach ($batch_set['operations'] as $operation) {
Chris@0 939 $queue->createItem($operation);
Chris@0 940 }
Chris@0 941
Chris@0 942 unset($batch_set['operations']);
Chris@0 943 }
Chris@0 944 }
Chris@0 945
Chris@0 946 /**
Chris@0 947 * Returns a queue object for a batch set.
Chris@0 948 *
Chris@0 949 * @param $batch_set
Chris@0 950 * The batch set.
Chris@0 951 *
Chris@0 952 * @return
Chris@0 953 * The queue object.
Chris@0 954 */
Chris@0 955 function _batch_queue($batch_set) {
Chris@0 956 static $queues;
Chris@0 957
Chris@0 958 if (!isset($queues)) {
Chris@0 959 $queues = [];
Chris@0 960 }
Chris@0 961
Chris@0 962 if (isset($batch_set['queue'])) {
Chris@0 963 $name = $batch_set['queue']['name'];
Chris@0 964 $class = $batch_set['queue']['class'];
Chris@0 965
Chris@0 966 if (!isset($queues[$class][$name])) {
Chris@0 967 $queues[$class][$name] = new $class($name, \Drupal::database());
Chris@0 968 }
Chris@0 969 return $queues[$class][$name];
Chris@0 970 }
Chris@0 971 }
Chris@0 972
Chris@0 973 /**
Chris@0 974 * @} End of "defgroup batch".
Chris@0 975 */