form.inc 38 KB

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