form.api.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. /**
  3. * @file
  4. * Callbacks and hooks related to form system.
  5. */
  6. /**
  7. * @addtogroup callbacks
  8. * @{
  9. */
  10. /**
  11. * Perform a single batch operation.
  12. *
  13. * Callback for batch_set().
  14. *
  15. * @param $multiple_params
  16. * Additional parameters specific to the batch. These are specified in the
  17. * array passed to batch_set().
  18. * @param array|\ArrayAccess $context
  19. * The batch context array, passed by reference. This contains the following
  20. * properties:
  21. * - 'finished': A float number between 0 and 1 informing the processing
  22. * engine of the completion level for the operation. 1 (or no value
  23. * explicitly set) means the operation is finished: the operation will not
  24. * be called again, and execution passes to the next operation or the
  25. * callback_batch_finished() implementation. Any other value causes this
  26. * operation to be called again; however it should be noted that the value
  27. * set here does not persist between executions of this callback: each time
  28. * it is set to 1 by default by the batch system.
  29. * - 'sandbox': This may be used by operations to persist data between
  30. * successive calls to the current operation. Any values set in
  31. * $context['sandbox'] will be there the next time this function is called
  32. * for the current operation. For example, an operation may wish to store a
  33. * pointer in a file or an offset for a large query. The 'sandbox' array key
  34. * is not initially set when this callback is first called, which makes it
  35. * useful for determining whether it is the first call of the callback or
  36. * not:
  37. * @code
  38. * if (empty($context['sandbox'])) {
  39. * // Perform set-up steps here.
  40. * }
  41. * @endcode
  42. * The values in the sandbox are stored and updated in the database between
  43. * http requests until the batch finishes processing. This avoids problems
  44. * if the user navigates away from the page before the batch finishes.
  45. * - 'message': A text message displayed in the progress page.
  46. * - 'results': The array of results gathered so far by the batch processing.
  47. * This array is highly useful for passing data between operations. After
  48. * all operations have finished, this is passed to callback_batch_finished()
  49. * where results may be referenced to display information to the end-user,
  50. * such as how many total items were processed.
  51. * It is discouraged to typehint this parameter as an array, to allow an
  52. * object implement \ArrayAccess to be passed.
  53. */
  54. function callback_batch_operation($multiple_params, &$context) {
  55. $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  56. $database = \Drupal::database();
  57. if (!isset($context['sandbox']['progress'])) {
  58. $context['sandbox']['progress'] = 0;
  59. $context['sandbox']['current_node'] = 0;
  60. $context['sandbox']['max'] = $database->query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  61. }
  62. // For this example, we decide that we can safely process
  63. // 5 nodes at a time without a timeout.
  64. $limit = 5;
  65. // With each pass through the callback, retrieve the next group of nids.
  66. $result = $database->queryRange("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, [':nid' => $context['sandbox']['current_node']]);
  67. foreach ($result as $row) {
  68. // Here we actually perform our processing on the current node.
  69. $node_storage->resetCache([$row['nid']]);
  70. $node = $node_storage->load($row['nid']);
  71. $node->value1 = $options1;
  72. $node->value2 = $options2;
  73. node_save($node);
  74. // Store some result for post-processing in the finished callback.
  75. $context['results'][] = $node->title;
  76. // Update our progress information.
  77. $context['sandbox']['progress']++;
  78. $context['sandbox']['current_node'] = $node->nid;
  79. $context['message'] = t('Now processing %node', ['%node' => $node->title]);
  80. }
  81. // Inform the batch engine that we are not finished,
  82. // and provide an estimation of the completion level we reached.
  83. if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  84. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  85. }
  86. }
  87. /**
  88. * Complete a batch process.
  89. *
  90. * Callback for batch_set().
  91. *
  92. * This callback may be specified in a batch to perform clean-up operations, or
  93. * to analyze the results of the batch operations.
  94. *
  95. * @param $success
  96. * A boolean indicating whether the batch has completed successfully.
  97. * @param $results
  98. * The value set in $context['results'] by callback_batch_operation().
  99. * @param $operations
  100. * If $success is FALSE, contains the operations that remained unprocessed.
  101. */
  102. function callback_batch_finished($success, $results, $operations) {
  103. if ($success) {
  104. // Here we do something meaningful with the results.
  105. $message = t("@count items were processed.", [
  106. '@count' => count($results),
  107. ]);
  108. $list = [
  109. '#theme' => 'item_list',
  110. '#items' => $results,
  111. ];
  112. $message .= drupal_render($list);
  113. \Drupal::messenger()->addStatus($message);
  114. }
  115. else {
  116. // An error occurred.
  117. // $operations contains the operations that remained unprocessed.
  118. $error_operation = reset($operations);
  119. $message = t('An error occurred while processing %error_operation with arguments: @arguments', [
  120. '%error_operation' => $error_operation[0],
  121. '@arguments' => print_r($error_operation[1], TRUE),
  122. ]);
  123. \Drupal::messenger()->addError($message);
  124. }
  125. }
  126. /**
  127. * @} End of "addtogroup callbacks".
  128. */
  129. /**
  130. * @addtogroup hooks
  131. * @{
  132. */
  133. /**
  134. * Alter the Ajax command data that is sent to the client.
  135. *
  136. * @param \Drupal\Core\Ajax\CommandInterface[] $data
  137. * An array of all the rendered commands that will be sent to the client.
  138. */
  139. function hook_ajax_render_alter(array &$data) {
  140. // Inject any new status messages into the content area.
  141. $status_messages = ['#type' => 'status_messages'];
  142. $command = new \Drupal\Core\Ajax\PrependCommand('#block-system-main .content', \Drupal::service('renderer')->renderRoot($status_messages));
  143. $data[] = $command->render();
  144. }
  145. /**
  146. * Perform alterations before a form is rendered.
  147. *
  148. * One popular use of this hook is to add form elements to the node form. When
  149. * altering a node form, the node entity can be retrieved by invoking
  150. * $form_state->getFormObject()->getEntity().
  151. *
  152. * Implementations are responsible for adding cache contexts/tags/max-age as
  153. * needed. See https://www.drupal.org/developing/api/8/cache.
  154. *
  155. * In addition to hook_form_alter(), which is called for all forms, there are
  156. * two more specific form hooks available. The first,
  157. * hook_form_BASE_FORM_ID_alter(), allows targeting of a form/forms via a base
  158. * form (if one exists). The second, hook_form_FORM_ID_alter(), can be used to
  159. * target a specific form directly.
  160. *
  161. * The call order is as follows: all existing form alter functions are called
  162. * for module A, then all for module B, etc., followed by all for any base
  163. * theme(s), and finally for the theme itself. The module order is determined
  164. * by system weight, then by module name.
  165. *
  166. * Within each module, form alter hooks are called in the following order:
  167. * first, hook_form_alter(); second, hook_form_BASE_FORM_ID_alter(); third,
  168. * hook_form_FORM_ID_alter(). So, for each module, the more general hooks are
  169. * called first followed by the more specific.
  170. *
  171. * @param $form
  172. * Nested array of form elements that comprise the form.
  173. * @param $form_state
  174. * The current state of the form. The arguments that
  175. * \Drupal::formBuilder()->getForm() was originally called with are available
  176. * in the array $form_state->getBuildInfo()['args'].
  177. * @param $form_id
  178. * String representing the name of the form itself. Typically this is the
  179. * name of the function that generated the form.
  180. *
  181. * @see hook_form_BASE_FORM_ID_alter()
  182. * @see hook_form_FORM_ID_alter()
  183. *
  184. * @ingroup form_api
  185. */
  186. function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  187. if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
  188. $upload_enabled_types = \Drupal::config('mymodule.settings')->get('upload_enabled_types');
  189. $form['workflow']['upload_' . $form['type']['#value']] = [
  190. '#type' => 'radios',
  191. '#title' => t('Attachments'),
  192. '#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
  193. '#options' => [t('Disabled'), t('Enabled')],
  194. ];
  195. // Add a custom submit handler to save the array of types back to the config file.
  196. $form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
  197. }
  198. }
  199. /**
  200. * Provide a form-specific alteration instead of the global hook_form_alter().
  201. *
  202. * Implementations are responsible for adding cache contexts/tags/max-age as
  203. * needed. See https://www.drupal.org/developing/api/8/cache.
  204. *
  205. * Modules can implement hook_form_FORM_ID_alter() to modify a specific form,
  206. * rather than implementing hook_form_alter() and checking the form ID, or
  207. * using long switch statements to alter multiple forms.
  208. *
  209. * Form alter hooks are called in the following order: hook_form_alter(),
  210. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  211. * hook_form_alter() for more details.
  212. *
  213. * @param $form
  214. * Nested array of form elements that comprise the form.
  215. * @param $form_state
  216. * The current state of the form. The arguments that
  217. * \Drupal::formBuilder()->getForm() was originally called with are available
  218. * in the array $form_state->getBuildInfo()['args'].
  219. * @param $form_id
  220. * String representing the name of the form itself. Typically this is the
  221. * name of the function that generated the form.
  222. *
  223. * @see hook_form_alter()
  224. * @see hook_form_BASE_FORM_ID_alter()
  225. * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm()
  226. *
  227. * @ingroup form_api
  228. */
  229. function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  230. // Modification for the form with the given form ID goes here. For example, if
  231. // FORM_ID is "user_register_form" this code would run only on the user
  232. // registration form.
  233. // Add a checkbox to registration form about agreeing to terms of use.
  234. $form['terms_of_use'] = [
  235. '#type' => 'checkbox',
  236. '#title' => t("I agree with the website's terms and conditions."),
  237. '#required' => TRUE,
  238. ];
  239. }
  240. /**
  241. * Provide a form-specific alteration for shared ('base') forms.
  242. *
  243. * Implementations are responsible for adding cache contexts/tags/max-age as
  244. * needed. See https://www.drupal.org/developing/api/8/cache.
  245. *
  246. * By default, when \Drupal::formBuilder()->getForm() is called, Drupal looks
  247. * for a function with the same name as the form ID, and uses that function to
  248. * build the form. In contrast, base forms allow multiple form IDs to be mapped
  249. * to a single base (also called 'factory') form function.
  250. *
  251. * Modules can implement hook_form_BASE_FORM_ID_alter() to modify a specific
  252. * base form, rather than implementing hook_form_alter() and checking for
  253. * conditions that would identify the shared form constructor.
  254. *
  255. * To identify the base form ID for a particular form (or to determine whether
  256. * one exists) check the $form_state. The base form ID is stored under
  257. * $form_state->getBuildInfo()['base_form_id'].
  258. *
  259. * Form alter hooks are called in the following order: hook_form_alter(),
  260. * hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See
  261. * hook_form_alter() for more details.
  262. *
  263. * @param $form
  264. * Nested array of form elements that comprise the form.
  265. * @param $form_state
  266. * The current state of the form.
  267. * @param $form_id
  268. * String representing the name of the form itself. Typically this is the
  269. * name of the function that generated the form.
  270. *
  271. * @see hook_form_alter()
  272. * @see hook_form_FORM_ID_alter()
  273. * @see \Drupal\Core\Form\FormBuilderInterface::prepareForm()
  274. *
  275. * @ingroup form_api
  276. */
  277. function hook_form_BASE_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  278. // Modification for the form with the given BASE_FORM_ID goes here. For
  279. // example, if BASE_FORM_ID is "node_form", this code would run on every
  280. // node form, regardless of node type.
  281. // Add a checkbox to the node form about agreeing to terms of use.
  282. $form['terms_of_use'] = [
  283. '#type' => 'checkbox',
  284. '#title' => t("I agree with the website's terms and conditions."),
  285. '#required' => TRUE,
  286. ];
  287. }
  288. /**
  289. * Alter batch information before a batch is processed.
  290. *
  291. * Called by batch_process() to allow modules to alter a batch before it is
  292. * processed.
  293. *
  294. * @param $batch
  295. * The associative array of batch information. See batch_set() for details on
  296. * what this could contain.
  297. *
  298. * @see batch_set()
  299. * @see batch_process()
  300. *
  301. * @ingroup batch
  302. */
  303. function hook_batch_alter(&$batch) {
  304. }
  305. /**
  306. * @} End of "addtogroup hooks".
  307. */