form.inc 40 KB

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