FormBuilderInterface.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. namespace Drupal\Core\Form;
  3. /**
  4. * Provides an interface for form building and processing.
  5. */
  6. interface FormBuilderInterface {
  7. /**
  8. * Request key for AJAX forms that submit to the form's original route.
  9. *
  10. * This constant is distinct from a "drupal_ajax" value for
  11. * \Drupal\Core\EventSubscriber\MainContentViewSubscriber::WRAPPER_FORMAT,
  12. * because that one is set for all AJAX submissions, including ones with
  13. * dedicated routes for which self::buildForm() should not exit early via a
  14. * \Drupal\Core\Form\FormAjaxException.
  15. *
  16. * @todo Re-evaluate the need for this constant after
  17. * https://www.drupal.org/node/2502785 and
  18. * https://www.drupal.org/node/2503429.
  19. */
  20. const AJAX_FORM_REQUEST = 'ajax_form';
  21. /**
  22. * Determines the ID of a form.
  23. *
  24. * @param \Drupal\Core\Form\FormInterface|string $form_arg
  25. * The value is identical to that of self::getForm()'s $form_arg argument.
  26. * @param \Drupal\Core\Form\FormStateInterface $form_state
  27. * The current state of the form.
  28. *
  29. * @return string
  30. * The unique string identifying the desired form.
  31. */
  32. public function getFormId($form_arg, FormStateInterface &$form_state);
  33. /**
  34. * Gets a renderable form array.
  35. *
  36. * This function should be used instead of self::buildForm() when $form_state
  37. * is not needed (i.e., when initially rendering the form) and is often
  38. * used as a menu callback.
  39. *
  40. * @param \Drupal\Core\Form\FormInterface|string $form_arg
  41. * The value must be one of the following:
  42. * - The name of a class that implements \Drupal\Core\Form\FormInterface.
  43. * - An instance of a class that implements \Drupal\Core\Form\FormInterface.
  44. * @param ...
  45. * Any additional arguments are passed on to the functions called by
  46. * \Drupal::formBuilder()->getForm(), including the unique form constructor
  47. * function. For example, the node_edit form requires that a node object is
  48. * passed in here when it is called. These are available to implementations
  49. * of hook_form_alter() and hook_form_FORM_ID_alter() as the array
  50. * $form_state->getBuildInfo()['args'].
  51. *
  52. * @return array
  53. * The form array.
  54. *
  55. * @see \Drupal\Core\Form\FormBuilderInterface::buildForm()
  56. */
  57. public function getForm($form_arg);
  58. /**
  59. * Builds and processes a form for a given form ID.
  60. *
  61. * The form may also be retrieved from the cache if the form was built in a
  62. * previous page load. The form is then passed on for processing, validation,
  63. * and submission if there is proper input.
  64. *
  65. * @param \Drupal\Core\Form\FormInterface|string $form_id
  66. * The value must be one of the following:
  67. * - The name of a class that implements \Drupal\Core\Form\FormInterface.
  68. * - An instance of a class that implements \Drupal\Core\Form\FormInterface.
  69. * @param \Drupal\Core\Form\FormStateInterface $form_state
  70. * The current state of the form.
  71. *
  72. * @return array
  73. * The rendered form. This function may also perform a redirect and hence
  74. * may not return at all depending upon the $form_state flags that were set.
  75. *
  76. * @throws \Drupal\Core\Form\FormAjaxException
  77. * Thrown when a form is triggered via an AJAX submission. It will be
  78. * handled by \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber.
  79. * @throws \Drupal\Core\Form\EnforcedResponseException
  80. * Thrown when a form builder returns a response directly, usually a
  81. * \Symfony\Component\HttpFoundation\RedirectResponse. It will be handled by
  82. * \Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber.
  83. *
  84. * @see self::redirectForm()
  85. */
  86. public function buildForm($form_id, FormStateInterface &$form_state);
  87. /**
  88. * Constructs a new $form from the information in $form_state.
  89. *
  90. * This is the key function for making multi-step forms advance from step to
  91. * step. It is called by self::processForm() when all user input processing,
  92. * including calling validation and submission handlers, for the request is
  93. * finished. If a validate or submit handler set $form_state->isRebuilding()
  94. * to TRUE, and if other conditions don't preempt a rebuild from happening,
  95. * then this function is called to generate a new $form, the next step in the
  96. * form workflow, to be returned for rendering.
  97. *
  98. * Ajax form submissions are almost always multi-step workflows, so that is
  99. * one common use-case during which form rebuilding occurs.
  100. *
  101. * @param string $form_id
  102. * The unique string identifying the desired form. If a function with that
  103. * name exists, it is called to build the form array.
  104. * @param \Drupal\Core\Form\FormStateInterface $form_state
  105. * The current state of the form.
  106. * @param array|null $old_form
  107. * (optional) A previously built $form. Used to retain the #build_id and
  108. * #action properties in Ajax callbacks and similar partial form rebuilds.
  109. * The only properties copied from $old_form are the ones which both exist
  110. * in $old_form and for which $form_state->getRebuildInfo()['copy'][PROPERTY]
  111. * is TRUE. If $old_form is not passed, the entire $form is rebuilt freshly.
  112. * 'rebuild_info' needs to be a separate top-level property next to
  113. * 'build_info', since the contained data must not be cached.
  114. *
  115. * @return array
  116. * The newly built form.
  117. *
  118. * @see self::processForm()
  119. */
  120. public function rebuildForm($form_id, FormStateInterface &$form_state, $old_form = NULL);
  121. /**
  122. * Retrieves, populates, and processes a form.
  123. *
  124. * This function allows you to supply values for form elements and submit a
  125. * form for processing. Compare to self::getForm(), which also builds and
  126. * processes a form, but does not allow you to supply values.
  127. *
  128. * There is no return value, but you can check to see if there are errors
  129. * by calling $form_state->getErrors().
  130. *
  131. * @param \Drupal\Core\Form\FormInterface|string $form_arg
  132. * The value must be one of the following:
  133. * - The name of a class that implements \Drupal\Core\Form\FormInterface.
  134. * - An instance of a class that implements \Drupal\Core\Form\FormInterface.
  135. * @param $form_state
  136. * The current state of the form. Most important is the
  137. * $form_state->getValues() collection, a tree of data used to simulate the
  138. * incoming \Drupal::request()->request information from a user's form
  139. * submission. If a key is not filled in $form_state->getValues(), then the
  140. * default value of the respective element is used. To submit an unchecked
  141. * checkbox or other control that browsers submit by not having a
  142. * \Drupal::request()->request entry, include the key, but set the value to
  143. * NULL.
  144. * @param ...
  145. * Any additional arguments are passed on to the functions called by
  146. * self::submitForm(), including the unique form constructor function.
  147. * For example, the node_edit form requires that a node object be passed
  148. * in here when it is called. Arguments that need to be passed by reference
  149. * should not be included here, but rather placed directly in the
  150. * $form_state build info array so that the reference can be preserved. For
  151. * example, a form builder function with the following signature:
  152. * @code
  153. * function mymodule_form($form, FormStateInterface &$form_state, &$object) {
  154. * }
  155. * @endcode
  156. * would be called via self::submitForm() as follows:
  157. * @code
  158. * $form_state->setValues($my_form_values);
  159. * $form_state->addBuildInfo('args', [&$object]);
  160. * \Drupal::formBuilder()->submitForm('mymodule_form', $form_state);
  161. * @endcode
  162. * For example:
  163. * @code
  164. * // register a new user
  165. * $form_state = new FormState();
  166. * $values['name'] = 'robo-user';
  167. * $values['mail'] = 'robouser@example.com';
  168. * $values['pass']['pass1'] = 'password';
  169. * $values['pass']['pass2'] = 'password';
  170. * $values['op'] = t('Create new account');
  171. * $form_state->setValues($values);
  172. * \Drupal::formBuilder()->submitForm('user_register_form', $form_state);
  173. * @endcode
  174. */
  175. public function submitForm($form_arg, FormStateInterface &$form_state);
  176. /**
  177. * Retrieves the structured array that defines a given form.
  178. *
  179. * @param string $form_id
  180. * The unique string identifying the desired form. If a function
  181. * with that name exists, it is called to build the form array.
  182. * @param \Drupal\Core\Form\FormStateInterface $form_state
  183. * The current state of the form, including the additional arguments to
  184. * self::getForm() or self::submitForm() in the 'args' component of the
  185. * array.
  186. *
  187. * @return mixed|\Symfony\Component\HttpFoundation\Response
  188. */
  189. public function retrieveForm($form_id, FormStateInterface &$form_state);
  190. /**
  191. * Processes a form submission.
  192. *
  193. * This function is the heart of form API. The form gets built, validated and
  194. * in appropriate cases, submitted and rebuilt.
  195. *
  196. * @param string $form_id
  197. * The unique string identifying the current form.
  198. * @param array $form
  199. * An associative array containing the structure of the form.
  200. * @param \Drupal\Core\Form\FormStateInterface $form_state
  201. * The current state of the form. This includes the current persistent
  202. * storage data for the form, and any data passed along by earlier steps
  203. * when displaying a multi-step form. Additional information, like the
  204. * sanitized \Drupal::request()->request data, is also accumulated here.
  205. *
  206. * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
  207. */
  208. public function processForm($form_id, &$form, FormStateInterface &$form_state);
  209. /**
  210. * Prepares a structured form array.
  211. *
  212. * Adds required elements, executes any hook_form_alter functions, and
  213. * optionally inserts a validation token to prevent tampering.
  214. *
  215. * @param string $form_id
  216. * A unique string identifying the form for validation, submission,
  217. * theming, and hook_form_alter functions.
  218. * @param array $form
  219. * An associative array containing the structure of the form.
  220. * @param \Drupal\Core\Form\FormStateInterface $form_state
  221. * The current state of the form. Passed in here so that hook_form_alter()
  222. * calls can use it, as well.
  223. */
  224. public function prepareForm($form_id, &$form, FormStateInterface &$form_state);
  225. /**
  226. * Builds and processes all elements in the structured form array.
  227. *
  228. * Adds any required properties to each element, maps the incoming input data
  229. * to the proper elements, and executes any #process handlers attached to a
  230. * specific element.
  231. *
  232. * This is one of the three primary functions that recursively iterates a form
  233. * array. This one does it for completing the form building process. The other
  234. * two are self::doValidateForm() (invoked via self::validateForm() and used
  235. * to invoke validation logic for each element) and drupal_render() (for
  236. * rendering each element). Each of these three pipelines provides ample
  237. * opportunity for modules to customize what happens. For example, during this
  238. * function's life cycle, the following functions get called for each element:
  239. * - $element['#value_callback']: A callable that implements how user input is
  240. * mapped to an element's #value property. This defaults to a function named
  241. * 'form_type_TYPE_value' where TYPE is $element['#type'].
  242. * - $element['#process']: An array of functions called after user input has
  243. * been mapped to the element's #value property. These functions can be used
  244. * to dynamically add child elements: for example, for the 'date' element
  245. * type, one of the functions in this array is form_process_datetime(),
  246. * which adds the individual 'date', and 'time'. child elements. These
  247. * functions can also be used to set additional properties or implement
  248. * special logic other than adding child elements: for example, for the
  249. * 'details' element type, one of the functions in this array is
  250. * form_process_details(), which adds the attributes and JavaScript needed
  251. * to make the details work in older browsers. The #process functions are
  252. * called in preorder traversal, meaning they are called for the parent
  253. * element first, then for the child elements.
  254. * - $element['#after_build']: An array of callables called after
  255. * self::doBuildForm() is done with its processing of the element. These are
  256. * called in postorder traversal, meaning they are called for the child
  257. * elements first, then for the parent element.
  258. * There are similar properties containing callback functions invoked by
  259. * self::doValidateForm() and drupal_render(), appropriate for those
  260. * operations.
  261. *
  262. * Developers are strongly encouraged to integrate the functionality needed by
  263. * their form or module within one of these three pipelines, using the
  264. * appropriate callback property, rather than implementing their own recursive
  265. * traversal of a form array. This facilitates proper integration between
  266. * multiple modules. For example, module developers are familiar with the
  267. * relative order in which hook_form_alter() implementations and #process
  268. * functions run. A custom traversal function that affects the building of a
  269. * form is likely to not integrate with hook_form_alter() and #process in the
  270. * expected way. Also, deep recursion within PHP is both slow and memory
  271. * intensive, so it is best to minimize how often it's done.
  272. *
  273. * As stated above, each element's #process functions are executed after its
  274. * #value has been set. This enables those functions to execute conditional
  275. * logic based on the current value. However, all of self::doBuildForm() runs
  276. * before self::validateForm() is called, so during #process function
  277. * execution, the element's #value has not yet been validated, so any code
  278. * that requires validated values must reside within a submit handler.
  279. *
  280. * As a security measure, user input is used for an element's #value only if
  281. * the element exists within $form, is not disabled (as per the #disabled
  282. * property), and can be accessed (as per the #access property, except that
  283. * forms submitted using self::submitForm() bypass #access restrictions). When
  284. * user input is ignored due to #disabled and #access restrictions, the
  285. * element's default value is used.
  286. *
  287. * Because of the preorder traversal, where #process functions of an element
  288. * run before user input for its child elements is processed, and because of
  289. * the Form API security of user input processing with respect to #access and
  290. * #disabled described above, this generally means that #process functions
  291. * should not use an element's (unvalidated) #value to affect the #disabled or
  292. * #access of child elements. Use-cases where a developer may be tempted to
  293. * implement such conditional logic usually fall into one of two categories:
  294. * - Where user input from the current submission must affect the structure of
  295. * a form, including properties like #access and #disabled that affect how
  296. * the next submission needs to be processed, a multi-step workflow is
  297. * needed. This is most commonly implemented with a submit handler setting
  298. * persistent data within $form_state based on *validated* values in
  299. * $form_state->getValues() and checking $form_state->isRebuilding(). The
  300. * form building functions must then be implemented to use the $form_state
  301. * to rebuild the form with the structure appropriate for the new state.
  302. * - Where user input must affect the rendering of the form without affecting
  303. * its structure, the necessary conditional rendering logic should reside
  304. * within functions that run during the rendering phase (#pre_render,
  305. * #theme, #theme_wrappers, and #post_render).
  306. *
  307. * @param string $form_id
  308. * A unique string identifying the form for validation, submission,
  309. * theming, and hook_form_alter functions.
  310. * @param array $element
  311. * An associative array containing the structure of the current element.
  312. * @param \Drupal\Core\Form\FormStateInterface $form_state
  313. * The current state of the form. In this context, it is used to accumulate
  314. * information about which button was clicked when the form was submitted,
  315. * as well as the sanitized \Drupal::request()->request data.
  316. *
  317. * @return array
  318. */
  319. public function doBuildForm($form_id, &$element, FormStateInterface &$form_state);
  320. }