PageRenderTime 59ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/core/lib/Drupal/Core/Form/form.api.php

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