FormBuilder.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Component\Utility\Crypt;
  4. use Drupal\Component\Utility\Html;
  5. use Drupal\Component\Utility\NestedArray;
  6. use Drupal\Component\Utility\UrlHelper;
  7. use Drupal\Core\Access\AccessResultInterface;
  8. use Drupal\Core\Access\CsrfTokenGenerator;
  9. use Drupal\Core\DependencyInjection\ClassResolverInterface;
  10. use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
  11. use Drupal\Core\Extension\ModuleHandlerInterface;
  12. use Drupal\Core\Form\Exception\BrokenPostRequestException;
  13. use Drupal\Core\Render\Element;
  14. use Drupal\Core\Render\ElementInfoManagerInterface;
  15. use Drupal\Core\Theme\ThemeManagerInterface;
  16. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  17. use Symfony\Component\HttpFoundation\FileBag;
  18. use Symfony\Component\HttpFoundation\RequestStack;
  19. use Symfony\Component\HttpFoundation\Response;
  20. /**
  21. * Provides form building and processing.
  22. *
  23. * @ingroup form_api
  24. */
  25. class FormBuilder implements FormBuilderInterface, FormValidatorInterface, FormSubmitterInterface, FormCacheInterface {
  26. /**
  27. * The module handler.
  28. *
  29. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  30. */
  31. protected $moduleHandler;
  32. /**
  33. * The event dispatcher.
  34. *
  35. * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
  36. */
  37. protected $eventDispatcher;
  38. /**
  39. * The request stack.
  40. *
  41. * @var \Symfony\Component\HttpFoundation\RequestStack
  42. */
  43. protected $requestStack;
  44. /**
  45. * The element info manager.
  46. *
  47. * @var \Drupal\Core\Render\ElementInfoManagerInterface
  48. */
  49. protected $elementInfo;
  50. /**
  51. * The CSRF token generator to validate the form token.
  52. *
  53. * @var \Drupal\Core\Access\CsrfTokenGenerator
  54. */
  55. protected $csrfToken;
  56. /**
  57. * The class resolver.
  58. *
  59. * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
  60. */
  61. protected $classResolver;
  62. /**
  63. * The current user.
  64. *
  65. * @var \Drupal\Core\Session\AccountInterface
  66. */
  67. protected $currentUser;
  68. /**
  69. * The theme manager.
  70. *
  71. * @var \Drupal\Core\Theme\ThemeManagerInterface
  72. */
  73. protected $themeManager;
  74. /**
  75. * @var \Drupal\Core\Form\FormValidatorInterface
  76. */
  77. protected $formValidator;
  78. /**
  79. * @var \Drupal\Core\Form\FormSubmitterInterface
  80. */
  81. protected $formSubmitter;
  82. /**
  83. * The form cache.
  84. *
  85. * @var \Drupal\Core\Form\FormCacheInterface
  86. */
  87. protected $formCache;
  88. /**
  89. * Defines element value callables which are safe to run even when the form
  90. * state has an invalid CSRF token.
  91. *
  92. * Excluded from this list on purpose:
  93. * - Drupal\file\Element\ManagedFile::valueCallback
  94. * - Drupal\Core\Datetime\Element\Datelist::valueCallback
  95. * - Drupal\Core\Datetime\Element\Datetime::valueCallback
  96. * - Drupal\Core\Render\Element\ImageButton::valueCallback
  97. * - Drupal\file\Plugin\Field\FieldWidget\FileWidget::value
  98. * - color_palette_color_value
  99. *
  100. * @var array
  101. */
  102. protected $safeCoreValueCallables = [
  103. 'Drupal\Core\Render\Element\Checkbox::valueCallback',
  104. 'Drupal\Core\Render\Element\Checkboxes::valueCallback',
  105. 'Drupal\Core\Render\Element\Email::valueCallback',
  106. 'Drupal\Core\Render\Element\FormElement::valueCallback',
  107. 'Drupal\Core\Render\Element\MachineName::valueCallback',
  108. 'Drupal\Core\Render\Element\Number::valueCallback',
  109. 'Drupal\Core\Render\Element\PathElement::valueCallback',
  110. 'Drupal\Core\Render\Element\Password::valueCallback',
  111. 'Drupal\Core\Render\Element\PasswordConfirm::valueCallback',
  112. 'Drupal\Core\Render\Element\Radio::valueCallback',
  113. 'Drupal\Core\Render\Element\Radios::valueCallback',
  114. 'Drupal\Core\Render\Element\Range::valueCallback',
  115. 'Drupal\Core\Render\Element\Search::valueCallback',
  116. 'Drupal\Core\Render\Element\Select::valueCallback',
  117. 'Drupal\Core\Render\Element\Tableselect::valueCallback',
  118. 'Drupal\Core\Render\Element\Table::valueCallback',
  119. 'Drupal\Core\Render\Element\Tel::valueCallback',
  120. 'Drupal\Core\Render\Element\Textarea::valueCallback',
  121. 'Drupal\Core\Render\Element\Textfield::valueCallback',
  122. 'Drupal\Core\Render\Element\Token::valueCallback',
  123. 'Drupal\Core\Render\Element\Url::valueCallback',
  124. 'Drupal\Core\Render\Element\Weight::valueCallback',
  125. ];
  126. /**
  127. * Constructs a new FormBuilder.
  128. *
  129. * @param \Drupal\Core\Form\FormValidatorInterface $form_validator
  130. * The form validator.
  131. * @param \Drupal\Core\Form\FormSubmitterInterface $form_submitter
  132. * The form submission processor.
  133. * @param \Drupal\Core\Form\FormCacheInterface $form_cache
  134. * The form cache.
  135. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  136. * The module handler.
  137. * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
  138. * The event dispatcher.
  139. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  140. * The request stack.
  141. * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
  142. * The class resolver.
  143. * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
  144. * The element info manager.
  145. * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
  146. * The theme manager.
  147. * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
  148. * The CSRF token generator.
  149. */
  150. public function __construct(FormValidatorInterface $form_validator, FormSubmitterInterface $form_submitter, FormCacheInterface $form_cache, ModuleHandlerInterface $module_handler, EventDispatcherInterface $event_dispatcher, RequestStack $request_stack, ClassResolverInterface $class_resolver, ElementInfoManagerInterface $element_info, ThemeManagerInterface $theme_manager, CsrfTokenGenerator $csrf_token = NULL) {
  151. $this->formValidator = $form_validator;
  152. $this->formSubmitter = $form_submitter;
  153. $this->formCache = $form_cache;
  154. $this->moduleHandler = $module_handler;
  155. $this->eventDispatcher = $event_dispatcher;
  156. $this->requestStack = $request_stack;
  157. $this->classResolver = $class_resolver;
  158. $this->elementInfo = $element_info;
  159. $this->csrfToken = $csrf_token;
  160. $this->themeManager = $theme_manager;
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function getFormId($form_arg, FormStateInterface &$form_state) {
  166. // If the $form_arg is the name of a class, instantiate it. Don't allow
  167. // arbitrary strings to be passed to the class resolver.
  168. if (is_string($form_arg) && class_exists($form_arg)) {
  169. $form_arg = $this->classResolver->getInstanceFromDefinition($form_arg);
  170. }
  171. if (!is_object($form_arg) || !($form_arg instanceof FormInterface)) {
  172. throw new \InvalidArgumentException("The form argument $form_arg is not a valid form.");
  173. }
  174. // Add the $form_arg as the callback object and determine the form ID.
  175. $form_state->setFormObject($form_arg);
  176. if ($form_arg instanceof BaseFormIdInterface) {
  177. $form_state->addBuildInfo('base_form_id', $form_arg->getBaseFormId());
  178. }
  179. return $form_arg->getFormId();
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function getForm($form_arg) {
  185. $form_state = new FormState();
  186. $args = func_get_args();
  187. // Remove $form_arg from the arguments.
  188. unset($args[0]);
  189. $form_state->addBuildInfo('args', array_values($args));
  190. return $this->buildForm($form_arg, $form_state);
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. public function buildForm($form_id, FormStateInterface &$form_state) {
  196. // Ensure the form ID is prepared.
  197. $form_id = $this->getFormId($form_id, $form_state);
  198. $request = $this->requestStack->getCurrentRequest();
  199. // Inform $form_state about the request method that's building it, so that
  200. // it can prevent persisting state changes during HTTP methods for which
  201. // that is disallowed by HTTP: GET and HEAD.
  202. $form_state->setRequestMethod($request->getMethod());
  203. // Initialize the form's user input. The user input should include only the
  204. // input meant to be treated as part of what is submitted to the form, so
  205. // we base it on the form's method rather than the request's method. For
  206. // example, when someone does a GET request for
  207. // /node/add/article?destination=foo, which is a form that expects its
  208. // submission method to be POST, the user input during the GET request
  209. // should be initialized to empty rather than to ['destination' => 'foo'].
  210. $input = $form_state->getUserInput();
  211. if (!isset($input)) {
  212. $input = $form_state->isMethodType('get') ? $request->query->all() : $request->request->all();
  213. $form_state->setUserInput($input);
  214. }
  215. if (isset($_SESSION['batch_form_state'])) {
  216. // We've been redirected here after a batch processing. The form has
  217. // already been processed, but needs to be rebuilt. See _batch_finished().
  218. $form_state = $_SESSION['batch_form_state'];
  219. unset($_SESSION['batch_form_state']);
  220. return $this->rebuildForm($form_id, $form_state);
  221. }
  222. // If the incoming input contains a form_build_id, we'll check the cache for
  223. // a copy of the form in question. If it's there, we don't have to rebuild
  224. // the form to proceed. In addition, if there is stored form_state data from
  225. // a previous step, we'll retrieve it so it can be passed on to the form
  226. // processing code.
  227. $check_cache = isset($input['form_id']) && $input['form_id'] == $form_id && !empty($input['form_build_id']);
  228. if ($check_cache) {
  229. $form = $this->getCache($input['form_build_id'], $form_state);
  230. }
  231. // If the previous bit of code didn't result in a populated $form object, we
  232. // are hitting the form for the first time and we need to build it from
  233. // scratch.
  234. if (!isset($form)) {
  235. // If we attempted to serve the form from cache, uncacheable $form_state
  236. // keys need to be removed after retrieving and preparing the form, except
  237. // any that were already set prior to retrieving the form.
  238. if ($check_cache) {
  239. $form_state_before_retrieval = clone $form_state;
  240. }
  241. $form = $this->retrieveForm($form_id, $form_state);
  242. $this->prepareForm($form_id, $form, $form_state);
  243. // self::setCache() removes uncacheable $form_state keys (see properties
  244. // in \Drupal\Core\Form\FormState) in order for multi-step forms to work
  245. // properly. This means that form processing logic for single-step forms
  246. // using $form_state->isCached() may depend on data stored in those keys
  247. // during self::retrieveForm()/self::prepareForm(), but form processing
  248. // should not depend on whether the form is cached or not, so $form_state
  249. // is adjusted to match what it would be after a
  250. // self::setCache()/self::getCache() sequence. These exceptions are
  251. // allowed to survive here:
  252. // - always_process: Does not make sense in conjunction with form caching
  253. // in the first place, since passing form_build_id as a GET parameter is
  254. // not desired.
  255. // - temporary: Any assigned data is expected to survives within the same
  256. // page request.
  257. if ($check_cache) {
  258. $cache_form_state = $form_state->getCacheableArray();
  259. $cache_form_state['always_process'] = $form_state->getAlwaysProcess();
  260. $cache_form_state['temporary'] = $form_state->getTemporary();
  261. $form_state = $form_state_before_retrieval;
  262. $form_state->setFormState($cache_form_state);
  263. }
  264. }
  265. // If this form is an AJAX request, disable all form redirects.
  266. $request = $this->requestStack->getCurrentRequest();
  267. if ($ajax_form_request = $request->query->has(static::AJAX_FORM_REQUEST)) {
  268. $form_state->disableRedirect();
  269. }
  270. // Now that we have a constructed form, process it. This is where:
  271. // - Element #process functions get called to further refine $form.
  272. // - User input, if any, gets incorporated in the #value property of the
  273. // corresponding elements and into $form_state->getValues().
  274. // - Validation and submission handlers are called.
  275. // - If this submission is part of a multistep workflow, the form is rebuilt
  276. // to contain the information of the next step.
  277. // - If necessary, the form and form state are cached or re-cached, so that
  278. // appropriate information persists to the next page request.
  279. // All of the handlers in the pipeline receive $form_state by reference and
  280. // can use it to know or update information about the state of the form.
  281. $response = $this->processForm($form_id, $form, $form_state);
  282. // In case the post request exceeds the configured allowed size
  283. // (post_max_size), the post request is potentially broken. Add some
  284. // protection against that and at the same time have a nice error message.
  285. if ($ajax_form_request && !$request->request->has('form_id')) {
  286. throw new BrokenPostRequestException($this->getFileUploadMaxSize());
  287. }
  288. // After processing the form, if this is an AJAX form request, interrupt
  289. // form rendering and return by throwing an exception that contains the
  290. // processed form and form state. This exception will be caught by
  291. // \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber::onException() and
  292. // then passed through
  293. // \Drupal\Core\Form\FormAjaxResponseBuilderInterface::buildResponse() to
  294. // build a proper AJAX response.
  295. // Only do this when the form ID matches, since there is no guarantee from
  296. // $ajax_form_request that it's an AJAX request for this particular form.
  297. if ($ajax_form_request && $form_state->isProcessingInput() && $request->request->get('form_id') == $form_id) {
  298. throw new FormAjaxException($form, $form_state);
  299. }
  300. // If the form returns a response, skip subsequent page construction by
  301. // throwing an exception.
  302. // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
  303. //
  304. // @todo Exceptions should not be used for code flow control. However, the
  305. // Form API does not integrate with the HTTP Kernel based architecture of
  306. // Drupal 8. In order to resolve this issue properly it is necessary to
  307. // completely separate form submission from rendering.
  308. // @see https://www.drupal.org/node/2367555
  309. if ($response instanceof Response) {
  310. throw new EnforcedResponseException($response);
  311. }
  312. // If this was a successful submission of a single-step form or the last
  313. // step of a multi-step form, then self::processForm() issued a redirect to
  314. // another page, or back to this page, but as a new request. Therefore, if
  315. // we're here, it means that this is either a form being viewed initially
  316. // before any user input, or there was a validation error requiring the form
  317. // to be re-displayed, or we're in a multi-step workflow and need to display
  318. // the form's next step. In any case, we have what we need in $form, and can
  319. // return it for rendering.
  320. return $form;
  321. }
  322. /**
  323. * {@inheritdoc}
  324. */
  325. public function rebuildForm($form_id, FormStateInterface &$form_state, $old_form = NULL) {
  326. $form = $this->retrieveForm($form_id, $form_state);
  327. // Only GET and POST are valid form methods. If the form receives its input
  328. // via POST, then $form_state must be persisted when it is rebuilt between
  329. // submissions. If the form receives its input via GET, then persisting
  330. // state is forbidden by $form_state->setCached(), and the form must use
  331. // the URL itself to transfer its state across steps. Although $form_state
  332. // throws an exception based on the request method rather than the form's
  333. // method, we base the decision to cache on the form method, because:
  334. // - It's the form method that defines what the form needs to do to manage
  335. // its state.
  336. // - rebuildForm() should only be called after successful input processing,
  337. // which means the request method matches the form method, and if not,
  338. // there's some other error, so it's ok if an exception is thrown.
  339. if ($form_state->isMethodType('POST')) {
  340. $form_state->setCached();
  341. }
  342. // If only parts of the form will be returned to the browser (e.g., Ajax or
  343. // RIA clients), or if the form already had a new build ID regenerated when
  344. // it was retrieved from the form cache, reuse the existing #build_id.
  345. // Otherwise, a new #build_id is generated, to not clobber the previous
  346. // build's data in the form cache; also allowing the user to go back to an
  347. // earlier build, make changes, and re-submit.
  348. // @see self::prepareForm()
  349. $rebuild_info = $form_state->getRebuildInfo();
  350. $enforce_old_build_id = isset($old_form['#build_id']) && !empty($rebuild_info['copy']['#build_id']);
  351. $old_form_is_mutable_copy = isset($old_form['#build_id_old']);
  352. if ($enforce_old_build_id || $old_form_is_mutable_copy) {
  353. $form['#build_id'] = $old_form['#build_id'];
  354. if ($old_form_is_mutable_copy) {
  355. $form['#build_id_old'] = $old_form['#build_id_old'];
  356. }
  357. }
  358. else {
  359. if (isset($old_form['#build_id'])) {
  360. $form['#build_id_old'] = $old_form['#build_id'];
  361. }
  362. $form['#build_id'] = 'form-' . Crypt::randomBytesBase64();
  363. }
  364. // #action defaults to $request->getRequestUri(), but in case of Ajax and
  365. // other partial rebuilds, the form is submitted to an alternate URL, and
  366. // the original #action needs to be retained.
  367. if (isset($old_form['#action']) && !empty($rebuild_info['copy']['#action'])) {
  368. $form['#action'] = $old_form['#action'];
  369. }
  370. $this->prepareForm($form_id, $form, $form_state);
  371. // Caching is normally done in self::processForm(), but what needs to be
  372. // cached is the $form structure before it passes through
  373. // self::doBuildForm(), so we need to do it here.
  374. // @todo For Drupal 8, find a way to avoid this code duplication.
  375. if ($form_state->isCached()) {
  376. $this->setCache($form['#build_id'], $form, $form_state);
  377. }
  378. // Clear out all group associations as these might be different when
  379. // re-rendering the form.
  380. $form_state->setGroups([]);
  381. // Return a fully built form that is ready for rendering.
  382. return $this->doBuildForm($form_id, $form, $form_state);
  383. }
  384. /**
  385. * {@inheritdoc}
  386. */
  387. public function getCache($form_build_id, FormStateInterface $form_state) {
  388. return $this->formCache->getCache($form_build_id, $form_state);
  389. }
  390. /**
  391. * {@inheritdoc}
  392. */
  393. public function setCache($form_build_id, $form, FormStateInterface $form_state) {
  394. $this->formCache->setCache($form_build_id, $form, $form_state);
  395. }
  396. /**
  397. * {@inheritdoc}
  398. */
  399. public function deleteCache($form_build_id) {
  400. $this->formCache->deleteCache($form_build_id);
  401. }
  402. /**
  403. * {@inheritdoc}
  404. */
  405. public function submitForm($form_arg, FormStateInterface &$form_state) {
  406. $build_info = $form_state->getBuildInfo();
  407. if (empty($build_info['args'])) {
  408. $args = func_get_args();
  409. // Remove $form and $form_state from the arguments.
  410. unset($args[0], $args[1]);
  411. $form_state->addBuildInfo('args', array_values($args));
  412. }
  413. // Populate FormState::$input with the submitted values before retrieving
  414. // the form, to be consistent with what self::buildForm() does for
  415. // non-programmatic submissions (form builder functions may expect it to be
  416. // there).
  417. $form_state->setUserInput($form_state->getValues());
  418. $form_state->setProgrammed();
  419. $form_id = $this->getFormId($form_arg, $form_state);
  420. $form = $this->retrieveForm($form_id, $form_state);
  421. // Programmed forms are always submitted.
  422. $form_state->setSubmitted();
  423. // Reset form validation.
  424. $form_state->setValidationEnforced();
  425. $form_state->clearErrors();
  426. $this->prepareForm($form_id, $form, $form_state);
  427. $this->processForm($form_id, $form, $form_state);
  428. }
  429. /**
  430. * {@inheritdoc}
  431. */
  432. public function retrieveForm($form_id, FormStateInterface &$form_state) {
  433. // Record the $form_id.
  434. $form_state->addBuildInfo('form_id', $form_id);
  435. // We save two copies of the incoming arguments: one for modules to use
  436. // when mapping form ids to constructor functions, and another to pass to
  437. // the constructor function itself.
  438. $build_info = $form_state->getBuildInfo();
  439. $args = $build_info['args'];
  440. $callback = [$form_state->getFormObject(), 'buildForm'];
  441. $form = [];
  442. // Assign a default CSS class name based on $form_id.
  443. // This happens here and not in self::prepareForm() in order to allow the
  444. // form constructor function to override or remove the default class.
  445. $form['#attributes']['class'][] = Html::getClass($form_id);
  446. // Same for the base form ID, if any.
  447. if (isset($build_info['base_form_id'])) {
  448. $form['#attributes']['class'][] = Html::getClass($build_info['base_form_id']);
  449. }
  450. // We need to pass $form_state by reference in order for forms to modify it,
  451. // since call_user_func_array() requires that referenced variables are
  452. // passed explicitly.
  453. $args = array_merge([$form, &$form_state], $args);
  454. $form = call_user_func_array($callback, $args);
  455. // If the form returns a response, skip subsequent page construction by
  456. // throwing an exception.
  457. // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
  458. //
  459. // @todo Exceptions should not be used for code flow control. However, the
  460. // Form API currently allows any form builder functions to return a
  461. // response.
  462. // @see https://www.drupal.org/node/2363189
  463. if ($form instanceof Response) {
  464. throw new EnforcedResponseException($form);
  465. }
  466. $form['#form_id'] = $form_id;
  467. return $form;
  468. }
  469. /**
  470. * {@inheritdoc}
  471. */
  472. public function processForm($form_id, &$form, FormStateInterface &$form_state) {
  473. $form_state->setValues([]);
  474. // With GET, these forms are always submitted if requested.
  475. if ($form_state->isMethodType('get') && $form_state->getAlwaysProcess()) {
  476. $input = $form_state->getUserInput();
  477. if (!isset($input['form_build_id'])) {
  478. $input['form_build_id'] = $form['#build_id'];
  479. }
  480. if (!isset($input['form_id'])) {
  481. $input['form_id'] = $form_id;
  482. }
  483. if (!isset($input['form_token']) && isset($form['#token'])) {
  484. $input['form_token'] = $this->csrfToken->get($form['#token']);
  485. }
  486. $form_state->setUserInput($input);
  487. }
  488. // self::doBuildForm() finishes building the form by calling element
  489. // #process functions and mapping user input, if any, to #value properties,
  490. // and also storing the values in $form_state->getValues(). We need to
  491. // retain the unprocessed $form in case it needs to be cached.
  492. $unprocessed_form = $form;
  493. $form = $this->doBuildForm($form_id, $form, $form_state);
  494. // Only process the input if we have a correct form submission.
  495. if ($form_state->isProcessingInput()) {
  496. // Form values for programmed form submissions typically do not include a
  497. // value for the submit button. But without a triggering element, a
  498. // potentially existing #limit_validation_errors property on the primary
  499. // submit button is not taken account. Therefore, check whether there is
  500. // exactly one submit button in the form, and if so, automatically use it
  501. // as triggering_element.
  502. $buttons = $form_state->getButtons();
  503. if ($form_state->isProgrammed() && !$form_state->getTriggeringElement() && count($buttons) == 1) {
  504. $form_state->setTriggeringElement(reset($buttons));
  505. }
  506. $this->formValidator->validateForm($form_id, $form, $form_state);
  507. // \Drupal\Component\Utility\Html::getUniqueId() maintains a cache of
  508. // element IDs it has seen, so it can prevent duplicates. We want to be
  509. // sure we reset that cache when a form is processed, so scenarios that
  510. // result in the form being built behind the scenes and again for the
  511. // browser don't increment all the element IDs needlessly.
  512. if (!FormState::hasAnyErrors()) {
  513. // In case of errors, do not break HTML IDs of other forms.
  514. Html::resetSeenIds();
  515. }
  516. // If there are no errors and the form is not rebuilding, submit the form.
  517. if (!$form_state->isRebuilding() && !FormState::hasAnyErrors()) {
  518. $submit_response = $this->formSubmitter->doSubmitForm($form, $form_state);
  519. // If this form was cached, delete it from the cache after submission.
  520. if ($form_state->isCached()) {
  521. $this->deleteCache($form['#build_id']);
  522. }
  523. // If the form submission directly returned a response, return it now.
  524. if ($submit_response) {
  525. return $submit_response;
  526. }
  527. }
  528. // Don't rebuild or cache form submissions invoked via self::submitForm().
  529. if ($form_state->isProgrammed()) {
  530. return;
  531. }
  532. // If $form_state->isRebuilding() has been set and input has been
  533. // processed without validation errors, we are in a multi-step workflow
  534. // that is not yet complete. A new $form needs to be constructed based on
  535. // the changes made to $form_state during this request. Normally, a submit
  536. // handler sets $form_state->isRebuilding() if a fully executed form
  537. // requires another step. However, for forms that have not been fully
  538. // executed (e.g., Ajax submissions triggered by non-buttons), there is no
  539. // submit handler to set $form_state->isRebuilding(). It would not make
  540. // sense to redisplay the identical form without an error for the user to
  541. // correct, so we also rebuild error-free non-executed forms, regardless
  542. // of $form_state->isRebuilding().
  543. // @todo Simplify this logic; considering Ajax and non-HTML front-ends,
  544. // along with element-level #submit properties, it makes no sense to
  545. // have divergent form execution based on whether the triggering element
  546. // has #executes_submit_callback set to TRUE.
  547. if (($form_state->isRebuilding() || !$form_state->isExecuted()) && !FormState::hasAnyErrors()) {
  548. // Form building functions (e.g., self::handleInputElement()) may use
  549. // $form_state->isRebuilding() to determine if they are running in the
  550. // context of a rebuild, so ensure it is set.
  551. $form_state->setRebuild();
  552. $form = $this->rebuildForm($form_id, $form_state, $form);
  553. }
  554. }
  555. // After processing the form, the form builder or a #process callback may
  556. // have called $form_state->setCached() to indicate that the form and form
  557. // state shall be cached. But the form may only be cached if
  558. // $form_state->disableCache() is not called. Only cache $form as it was
  559. // prior to self::doBuildForm(), because self::doBuildForm() must run for
  560. // each request to accommodate new user input. Rebuilt forms are not cached
  561. // here, because self::rebuildForm() already takes care of that.
  562. if (!$form_state->isRebuilding() && $form_state->isCached()) {
  563. $this->setCache($form['#build_id'], $unprocessed_form, $form_state);
  564. }
  565. }
  566. /**
  567. * #lazy_builder callback; renders a form action URL.
  568. *
  569. * @return array
  570. * A renderable array representing the form action.
  571. */
  572. public function renderPlaceholderFormAction() {
  573. return [
  574. '#type' => 'markup',
  575. '#markup' => $this->buildFormAction(),
  576. '#cache' => ['contexts' => ['url.path', 'url.query_args']],
  577. ];
  578. }
  579. /**
  580. * #lazy_builder callback; renders form CSRF token.
  581. *
  582. * @param string $placeholder
  583. * A string containing a placeholder, matching the value of the form's
  584. * #token.
  585. *
  586. * @return array
  587. * A renderable array containing the CSRF token.
  588. */
  589. public function renderFormTokenPlaceholder($placeholder) {
  590. return [
  591. '#markup' => $this->csrfToken->get($placeholder),
  592. '#cache' => [
  593. 'contexts' => [
  594. 'session',
  595. ],
  596. ],
  597. ];
  598. }
  599. /**
  600. * {@inheritdoc}
  601. */
  602. public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
  603. $user = $this->currentUser();
  604. $form['#type'] = 'form';
  605. // Only update the action if it is not already set.
  606. if (!isset($form['#action'])) {
  607. // Instead of setting an actual action URL, we set the placeholder, which
  608. // will be replaced at the very last moment. This ensures forms with
  609. // dynamically generated action URLs don't have poor cacheability.
  610. // Use the proper API to generate the placeholder, when we have one. See
  611. // https://www.drupal.org/node/2562341. The placholder uses a fixed string
  612. // that is Crypt::hashBase64('Drupal\Core\Form\FormBuilder::prepareForm');
  613. $placeholder = 'form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM';
  614. $form['#attached']['placeholders'][$placeholder] = [
  615. '#lazy_builder' => ['form_builder:renderPlaceholderFormAction', []],
  616. ];
  617. $form['#action'] = $placeholder;
  618. }
  619. // Fix the form method, if it is 'get' in $form_state, but not in $form.
  620. if ($form_state->isMethodType('get') && !isset($form['#method'])) {
  621. $form['#method'] = 'get';
  622. }
  623. // GET forms should not use a CSRF token.
  624. if (isset($form['#method']) && $form['#method'] === 'get') {
  625. // Merges in a default, this means if you've explicitly set #token to the
  626. // the $form_id on a GET form, which we don't recommend, it will work.
  627. $form += [
  628. '#token' => FALSE,
  629. ];
  630. }
  631. // Generate a new #build_id for this form, if none has been set already.
  632. // The form_build_id is used as key to cache a particular build of the form.
  633. // For multi-step forms, this allows the user to go back to an earlier
  634. // build, make changes, and re-submit.
  635. // @see self::buildForm()
  636. // @see self::rebuildForm()
  637. if (!isset($form['#build_id'])) {
  638. $form['#build_id'] = 'form-' . Crypt::randomBytesBase64();
  639. }
  640. $form['form_build_id'] = [
  641. '#type' => 'hidden',
  642. '#value' => $form['#build_id'],
  643. '#id' => $form['#build_id'],
  644. '#name' => 'form_build_id',
  645. // Form processing and validation requires this value, so ensure the
  646. // submitted form value appears literally, regardless of custom #tree
  647. // and #parents being set elsewhere.
  648. '#parents' => ['form_build_id'],
  649. // Prevent user agents from prefilling the build id with earlier values.
  650. // When the ajax command "update_build_id" is executed, the user agent
  651. // will assume that a user interaction changed the field. Upon a soft
  652. // reload of the page, the previous build id will be restored in the
  653. // input, causing subsequent ajax callbacks to access the wrong cached
  654. // form build. Setting the autocomplete attribute to "off" will tell the
  655. // user agent to never reuse the value.
  656. // @see https://www.w3.org/TR/2011/WD-html5-20110525/common-input-element-attributes.html#the-autocomplete-attribute
  657. '#attributes' => [
  658. 'autocomplete' => 'off',
  659. ],
  660. ];
  661. // Add a token, based on either #token or form_id, to any form displayed to
  662. // authenticated users. This ensures that any submitted form was actually
  663. // requested previously by the user and protects against cross site request
  664. // forgeries.
  665. // This does not apply to programmatically submitted forms. Furthermore,
  666. // since tokens are session-bound and forms displayed to anonymous users are
  667. // very likely cached, we cannot assign a token for them.
  668. // During installation, there is no $user yet.
  669. // Form constructors may explicitly set #token to FALSE when cross site
  670. // request forgery is irrelevant to the form, such as search forms.
  671. if ($form_state->isProgrammed() || (isset($form['#token']) && $form['#token'] === FALSE)) {
  672. unset($form['#token']);
  673. }
  674. else {
  675. $form['#cache']['contexts'][] = 'user.roles:authenticated';
  676. if ($user && $user->isAuthenticated()) {
  677. // Generate a public token based on the form id.
  678. // Generates a placeholder based on the form ID.
  679. $placeholder = 'form_token_placeholder_' . Crypt::hashBase64($form_id);
  680. $form['#token'] = $placeholder;
  681. $form['form_token'] = [
  682. '#id' => Html::getUniqueId('edit-' . $form_id . '-form-token'),
  683. '#type' => 'token',
  684. '#default_value' => $placeholder,
  685. // Form processing and validation requires this value, so ensure the
  686. // submitted form value appears literally, regardless of custom #tree
  687. // and #parents being set elsewhere.
  688. '#parents' => ['form_token'],
  689. // Instead of setting an actual CSRF token, we've set the placeholder
  690. // in form_token's #default_value and #placeholder. These will be
  691. // replaced at the very last moment. This ensures forms with a CSRF
  692. // token don't have poor cacheability.
  693. '#attached' => [
  694. 'placeholders' => [
  695. $placeholder => [
  696. '#lazy_builder' => ['form_builder:renderFormTokenPlaceholder', [$placeholder]]
  697. ]
  698. ]
  699. ],
  700. '#cache' => [
  701. 'max-age' => 0,
  702. ],
  703. ];
  704. }
  705. }
  706. if (isset($form_id)) {
  707. $form['form_id'] = [
  708. '#type' => 'hidden',
  709. '#value' => $form_id,
  710. '#id' => Html::getUniqueId("edit-$form_id"),
  711. // Form processing and validation requires this value, so ensure the
  712. // submitted form value appears literally, regardless of custom #tree
  713. // and #parents being set elsewhere.
  714. '#parents' => ['form_id'],
  715. ];
  716. }
  717. if (!isset($form['#id'])) {
  718. $form['#id'] = Html::getUniqueId($form_id);
  719. // Provide a selector usable by JavaScript. As the ID is unique, its not
  720. // possible to rely on it in JavaScript.
  721. $form['#attributes']['data-drupal-selector'] = Html::getId($form_id);
  722. }
  723. $form += $this->elementInfo->getInfo('form');
  724. $form += ['#tree' => FALSE, '#parents' => []];
  725. $form['#validate'][] = '::validateForm';
  726. $form['#submit'][] = '::submitForm';
  727. $build_info = $form_state->getBuildInfo();
  728. // If no #theme has been set, automatically apply theme suggestions.
  729. // The form theme hook itself, which is rendered by form.html.twig,
  730. // is in #theme_wrappers. Therefore, the #theme function only has to care
  731. // for rendering the inner form elements, not the form itself.
  732. if (!isset($form['#theme'])) {
  733. $form['#theme'] = [$form_id];
  734. if (isset($build_info['base_form_id'])) {
  735. $form['#theme'][] = $build_info['base_form_id'];
  736. }
  737. }
  738. // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
  739. // hook_form_FORM_ID_alter() implementations.
  740. $hooks = ['form'];
  741. if (isset($build_info['base_form_id'])) {
  742. $hooks[] = 'form_' . $build_info['base_form_id'];
  743. }
  744. $hooks[] = 'form_' . $form_id;
  745. $this->moduleHandler->alter($hooks, $form, $form_state, $form_id);
  746. $this->themeManager->alter($hooks, $form, $form_state, $form_id);
  747. }
  748. /**
  749. * Builds the $form['#action'].
  750. *
  751. * @return string
  752. * The URL to be used as the $form['#action'].
  753. */
  754. protected function buildFormAction() {
  755. // @todo Use <current> instead of the master request in
  756. // https://www.drupal.org/node/2505339.
  757. $request = $this->requestStack->getMasterRequest();
  758. $request_uri = $request->getRequestUri();
  759. // Prevent cross site requests via the Form API by using an absolute URL
  760. // when the request uri starts with multiple slashes..
  761. if (strpos($request_uri, '//') === 0) {
  762. $request_uri = $request->getUri();
  763. }
  764. // @todo Remove this parsing once these are removed from the request in
  765. // https://www.drupal.org/node/2504709.
  766. $parsed = UrlHelper::parse($request_uri);
  767. unset($parsed['query'][static::AJAX_FORM_REQUEST], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
  768. return $parsed['path'] . ($parsed['query'] ? ('?' . UrlHelper::buildQuery($parsed['query'])) : '');
  769. }
  770. /**
  771. * {@inheritdoc}
  772. */
  773. public function setInvalidTokenError(FormStateInterface $form_state) {
  774. $this->formValidator->setInvalidTokenError($form_state);
  775. }
  776. /**
  777. * {@inheritdoc}
  778. */
  779. public function validateForm($form_id, &$form, FormStateInterface &$form_state) {
  780. $this->formValidator->validateForm($form_id, $form, $form_state);
  781. }
  782. /**
  783. * {@inheritdoc}
  784. */
  785. public function redirectForm(FormStateInterface $form_state) {
  786. return $this->formSubmitter->redirectForm($form_state);
  787. }
  788. /**
  789. * {@inheritdoc}
  790. */
  791. public function executeValidateHandlers(&$form, FormStateInterface &$form_state) {
  792. $this->formValidator->executeValidateHandlers($form, $form_state);
  793. }
  794. /**
  795. * {@inheritdoc}
  796. */
  797. public function executeSubmitHandlers(&$form, FormStateInterface &$form_state) {
  798. $this->formSubmitter->executeSubmitHandlers($form, $form_state);
  799. }
  800. /**
  801. * {@inheritdoc}
  802. */
  803. public function doSubmitForm(&$form, FormStateInterface &$form_state) {
  804. throw new \LogicException('Use FormBuilderInterface::processForm() instead.');
  805. }
  806. /**
  807. * {@inheritdoc}
  808. */
  809. public function doBuildForm($form_id, &$element, FormStateInterface &$form_state) {
  810. // Initialize as unprocessed.
  811. $element['#processed'] = FALSE;
  812. // Use element defaults.
  813. if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = $this->elementInfo->getInfo($element['#type']))) {
  814. // Overlay $info onto $element, retaining preexisting keys in $element.
  815. $element += $info;
  816. $element['#defaults_loaded'] = TRUE;
  817. }
  818. // Assign basic defaults common for all form elements.
  819. $element += [
  820. '#required' => FALSE,
  821. '#attributes' => [],
  822. '#title_display' => 'before',
  823. '#description_display' => 'after',
  824. '#errors' => NULL,
  825. ];
  826. // Special handling if we're on the top level form element.
  827. if (isset($element['#type']) && $element['#type'] == 'form') {
  828. if (!empty($element['#https']) && !UrlHelper::isExternal($element['#action'])) {
  829. global $base_root;
  830. // Not an external URL so ensure that it is secure.
  831. $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
  832. }
  833. // Store a reference to the complete form in $form_state prior to building
  834. // the form. This allows advanced #process and #after_build callbacks to
  835. // perform changes elsewhere in the form.
  836. $form_state->setCompleteForm($element);
  837. // Set a flag if we have a correct form submission. This is always TRUE
  838. // for programmed forms coming from self::submitForm(), or if the form_id
  839. // coming from the POST data is set and matches the current form_id.
  840. $input = $form_state->getUserInput();
  841. if ($form_state->isProgrammed() || (!empty($input) && (isset($input['form_id']) && ($input['form_id'] == $form_id)))) {
  842. $form_state->setProcessInput();
  843. if (isset($element['#token'])) {
  844. $input = $form_state->getUserInput();
  845. if (empty($input['form_token']) || !$this->csrfToken->validate($input['form_token'], $element['#token'])) {
  846. // Set an early form error to block certain input processing since
  847. // that opens the door for CSRF vulnerabilities.
  848. $this->setInvalidTokenError($form_state);
  849. // This value is checked in self::handleInputElement().
  850. $form_state->setInvalidToken(TRUE);
  851. // Make sure file uploads do not get processed.
  852. $this->requestStack->getCurrentRequest()->files = new FileBag();
  853. }
  854. }
  855. }
  856. else {
  857. $form_state->setProcessInput(FALSE);
  858. }
  859. // All form elements should have an #array_parents property.
  860. $element['#array_parents'] = [];
  861. }
  862. if (!isset($element['#id'])) {
  863. $unprocessed_id = 'edit-' . implode('-', $element['#parents']);
  864. $element['#id'] = Html::getUniqueId($unprocessed_id);
  865. // Provide a selector usable by JavaScript. As the ID is unique, its not
  866. // possible to rely on it in JavaScript.
  867. $element['#attributes']['data-drupal-selector'] = Html::getId($unprocessed_id);
  868. }
  869. else {
  870. // Provide a selector usable by JavaScript. As the ID is unique, its not
  871. // possible to rely on it in JavaScript.
  872. $element['#attributes']['data-drupal-selector'] = Html::getId($element['#id']);
  873. }
  874. // Add the aria-describedby attribute to associate the form control with its
  875. // description.
  876. if (!empty($element['#description'])) {
  877. $element['#attributes']['aria-describedby'] = $element['#id'] . '--description';
  878. }
  879. // Handle input elements.
  880. if (!empty($element['#input'])) {
  881. $this->handleInputElement($form_id, $element, $form_state);
  882. }
  883. // Allow for elements to expand to multiple elements, e.g., radios,
  884. // checkboxes and files.
  885. if (isset($element['#process']) && !$element['#processed']) {
  886. foreach ($element['#process'] as $callback) {
  887. $complete_form = &$form_state->getCompleteForm();
  888. $element = call_user_func_array($form_state->prepareCallback($callback), [&$element, &$form_state, &$complete_form]);
  889. }
  890. $element['#processed'] = TRUE;
  891. }
  892. // We start off assuming all form elements are in the correct order.
  893. $element['#sorted'] = TRUE;
  894. // Recurse through all child elements.
  895. $count = 0;
  896. if (isset($element['#access'])) {
  897. $access = $element['#access'];
  898. $inherited_access = NULL;
  899. if (($access instanceof AccessResultInterface && !$access->isAllowed()) || $access === FALSE) {
  900. $inherited_access = $access;
  901. }
  902. }
  903. foreach (Element::children($element) as $key) {
  904. // Prior to checking properties of child elements, their default
  905. // properties need to be loaded.
  906. if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = $this->elementInfo->getInfo($element[$key]['#type']))) {
  907. $element[$key] += $info;
  908. $element[$key]['#defaults_loaded'] = TRUE;
  909. }
  910. // Don't squash an existing tree value.
  911. if (!isset($element[$key]['#tree'])) {
  912. $element[$key]['#tree'] = $element['#tree'];
  913. }
  914. // Children inherit #access from parent.
  915. if (isset($inherited_access)) {
  916. $element[$key]['#access'] = $inherited_access;
  917. }
  918. // Make child elements inherit their parent's #disabled and #allow_focus
  919. // values unless they specify their own.
  920. foreach (['#disabled', '#allow_focus'] as $property) {
  921. if (isset($element[$property]) && !isset($element[$key][$property])) {
  922. $element[$key][$property] = $element[$property];
  923. }
  924. }
  925. // Don't squash existing parents value.
  926. if (!isset($element[$key]['#parents'])) {
  927. // Check to see if a tree of child elements is present. If so,
  928. // continue down the tree if required.
  929. $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], [$key]) : [$key];
  930. }
  931. // Ensure #array_parents follows the actual form structure.
  932. $array_parents = $element['#array_parents'];
  933. $array_parents[] = $key;
  934. $element[$key]['#array_parents'] = $array_parents;
  935. // Assign a decimal placeholder weight to preserve original array order.
  936. if (!isset($element[$key]['#weight'])) {
  937. $element[$key]['#weight'] = $count / 1000;
  938. }
  939. else {
  940. // If one of the child elements has a weight then we will need to sort
  941. // later.
  942. unset($element['#sorted']);
  943. }
  944. $element[$key] = $this->doBuildForm($form_id, $element[$key], $form_state);
  945. $count++;
  946. }
  947. // The #after_build flag allows any piece of a form to be altered
  948. // after normal input parsing has been completed.
  949. if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
  950. foreach ($element['#after_build'] as $callback) {
  951. $element = call_user_func_array($form_state->prepareCallback($callback), [$element, &$form_state]);
  952. }
  953. $element['#after_build_done'] = TRUE;
  954. }
  955. // If there is a file element, we need to flip a flag so later the
  956. // form encoding can be set.
  957. if (isset($element['#type']) && $element['#type'] == 'file') {
  958. $form_state->setHasFileElement();
  959. }
  960. // Final tasks for the form element after self::doBuildForm() has run for
  961. // all other elements.
  962. if (isset($element['#type']) && $element['#type'] == 'form') {
  963. // If there is a file element, we set the form encoding.
  964. if ($form_state->hasFileElement()) {
  965. $element['#attributes']['enctype'] = 'multipart/form-data';
  966. }
  967. // Allow Ajax submissions to the form action to bypass verification. This
  968. // is especially useful for multipart forms, which cannot be verified via
  969. // a response header.
  970. $element['#attached']['drupalSettings']['ajaxTrustedUrl'][$element['#action']] = TRUE;
  971. // If a form contains a single textfield, and the ENTER key is pressed
  972. // within it, Internet Explorer submits the form with no POST data
  973. // identifying any submit button. Other browsers submit POST data as
  974. // though the user clicked the first button. Therefore, to be as
  975. // consistent as we can be across browsers, if no 'triggering_element' has
  976. // been identified yet, default it to the first button.
  977. $buttons = $form_state->getButtons();
  978. if (!$form_state->isProgrammed() && !$form_state->getTriggeringElement() && !empty($buttons)) {
  979. $form_state->setTriggeringElement($buttons[0]);
  980. }
  981. $triggering_element = $form_state->getTriggeringElement();
  982. // If the triggering element specifies "button-level" validation and
  983. // submit handlers to run instead of the default form-level ones, then add
  984. // those to the form state.
  985. if (isset($triggering_element['#validate'])) {
  986. $form_state->setValidateHandlers($triggering_element['#validate']);
  987. }
  988. if (isset($triggering_element['#submit'])) {
  989. $form_state->setSubmitHandlers($triggering_element['#submit']);
  990. }
  991. // If the triggering element executes submit handlers, then set the form
  992. // state key that's needed for those handlers to run.
  993. if (!empty($triggering_element['#executes_submit_callback'])) {
  994. $form_state->setSubmitted();
  995. }
  996. // Special processing if the triggering element is a button.
  997. if (!empty($triggering_element['#is_button'])) {
  998. // Because there are several ways in which the triggering element could
  999. // have been determined (including from input variables set by
  1000. // JavaScript or fallback behavior implemented for IE), and because
  1001. // buttons often have their #name property not derived from their
  1002. // #parents property, we can't assume that input processing that's
  1003. // happened up until here has resulted in
  1004. // $form_state->getValue(BUTTON_NAME) being set. But it's common for
  1005. // forms to have several buttons named 'op' and switch on
  1006. // $form_state->getValue('op') during submit handler execution.
  1007. $form_state->setValue($triggering_element['#name'], $triggering_element['#value']);
  1008. }
  1009. }
  1010. return $element;
  1011. }
  1012. /**
  1013. * Helper function to normalize the different callable formats.
  1014. *
  1015. * @param callable $value_callable
  1016. * The callable to be checked.
  1017. *
  1018. * @return bool
  1019. * TRUE if the callable is safe even if the CSRF token is invalid, FALSE
  1020. * otherwise.
  1021. */
  1022. protected function valueCallableIsSafe(callable $value_callable) {
  1023. // The same static class method callable may be formatted in two array and
  1024. // two string forms:
  1025. // ['\Classname', 'methodname']
  1026. // ['Classname', 'methodname']
  1027. // '\Classname::methodname'
  1028. // 'Classname::methodname'
  1029. if (is_callable($value_callable, FALSE, $callable_name)) {
  1030. // The third parameter of is_callable() is set to a string form, but we
  1031. // still have to normalize further by stripping a leading '\'.
  1032. return in_array(ltrim($callable_name, '\\'), $this->safeCoreValueCallables);
  1033. }
  1034. return FALSE;
  1035. }
  1036. /**
  1037. * Adds the #name and #value properties of an input element before rendering.
  1038. */
  1039. protected function handleInputElement($form_id, &$element, FormStateInterface &$form_state) {
  1040. if (!isset($element['#name'])) {
  1041. $name = array_shift($element['#parents']);
  1042. $element['#name'] = $name;
  1043. if ($element['#type'] == 'file') {
  1044. // To make it easier to handle files in file.inc, we place all
  1045. // file fields in the 'files' array. Also, we do not support
  1046. // nested file names.
  1047. // @todo Remove this files prefix now?
  1048. $element['#name'] = 'files[' . $element['#name'] . ']';
  1049. }
  1050. elseif (count($element['#parents'])) {
  1051. $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
  1052. }
  1053. array_unshift($element['#parents'], $name);
  1054. }
  1055. // Setting #disabled to TRUE results in user input being ignored regardless
  1056. // of how the element is themed or whether JavaScript is used to change the
  1057. // control's attributes. However, it's good UI to let the user know that
  1058. // input is not wanted for the control. HTML supports two attributes for:
  1059. // this: http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form
  1060. // wants to start a control off with one of these attributes for UI
  1061. // purposes, only, but still allow input to be processed if it's submitted,
  1062. // it can set the desired attribute in #attributes directly rather than
  1063. // using #disabled. However, developers should think carefully about the
  1064. // accessibility implications of doing so: if the form expects input to be
  1065. // enterable under some condition triggered by JavaScript, how would someone
  1066. // who has JavaScript disabled trigger that condition? Instead, developers
  1067. // should consider whether a multi-step form would be more appropriate
  1068. // (#disabled can be changed from step to step). If one still decides to use
  1069. // JavaScript to affect when a control is enabled, then it is best for
  1070. // accessibility for the control to be enabled in the HTML, and disabled by
  1071. // JavaScript on document ready.
  1072. if (!empty($element['#disabled'])) {
  1073. if (!empty($element['#allow_focus'])) {
  1074. $element['#attributes']['readonly'] = 'readonly';
  1075. }
  1076. else {
  1077. $element['#attributes']['disabled'] = 'disabled';
  1078. }
  1079. }
  1080. // With JavaScript or other easy hacking, input can be submitted even for
  1081. // elements with #access=FALSE or #disabled=TRUE. For security, these must
  1082. // not be processed. Forms that set #disabled=TRUE on an element do not
  1083. // expect input for the element, and even forms submitted with
  1084. // self::submitForm() must not be able to get around this. Forms that set
  1085. // #access=FALSE on an element usually allow access for some users, so forms
  1086. // submitted with self::submitForm() may bypass access restriction and be
  1087. // treated as high-privilege users instead.
  1088. $process_input = empty($element['#disabled']) && (($form_state->isProgrammed() && $form_state->isBypassingProgrammedAccessChecks()) || ($form_state->isProcessingInput() && (!isset($element['#access']) || $element['#access'])));
  1089. // Set the element's #value property.
  1090. if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
  1091. // @todo Once all elements are converted to plugins in
  1092. // https://www.drupal.org/node/2311393, rely on
  1093. // $element['#value_callback'] directly.
  1094. $value_callable = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
  1095. if (!is_callable($value_callable)) {
  1096. $value_callable = '\Drupal\Core\Render\Element\FormElement::valueCallback';
  1097. }
  1098. if ($process_input) {
  1099. // Get the input for the current element. NULL values in the input need
  1100. // to be explicitly distinguished from missing input. (see below)
  1101. $input_exists = NULL;
  1102. $input = NestedArray::getValue($form_state->getUserInput(), $element['#parents'], $input_exists);
  1103. // For browser-submitted forms, the submitted values do not contain
  1104. // values for certain elements (empty multiple select, unchecked
  1105. // checkbox). During initial form processing, we add explicit NULL
  1106. // values for such elements in FormState::$input. When rebuilding the
  1107. // form, we can distinguish elements having NULL input from elements
  1108. // that were not part of the initially submitted form and can therefore
  1109. // use default values for the latter, if required. Programmatically
  1110. // submitted forms can submit explicit NULL values when calling
  1111. // self::submitForm() so we do not modify FormState::$input for them.
  1112. if (!$input_exists && !$form_state->isRebuilding() && !$form_state->isProgrammed()) {
  1113. // Add the necessary parent keys to FormState::$input and sets the
  1114. // element's input value to NULL.
  1115. NestedArray::setValue($form_state->getUserInput(), $element['#parents'], NULL);
  1116. $input_exists = TRUE;
  1117. }
  1118. // If we have input for the current element, assign it to the #value
  1119. // property, optionally filtered through $value_callback.
  1120. if ($input_exists) {
  1121. // Skip all value callbacks except safe ones like text if the CSRF
  1122. // token was invalid.
  1123. if (!$form_state->hasInvalidToken() || $this->valueCallableIsSafe($value_callable)) {
  1124. $element['#value'] = call_user_func_array($value_callable, [&$element, $input, &$form_state]);
  1125. }
  1126. else {
  1127. $input = NULL;
  1128. }
  1129. if (!isset($element['#value']) && isset($input)) {
  1130. $element['#value'] = $input;
  1131. }
  1132. }
  1133. // Mark all posted values for validation.
  1134. if (isset($element['#value']) || (!empty($element['#required']))) {
  1135. $element['#needs_validation'] = TRUE;
  1136. }
  1137. }
  1138. // Load defaults.
  1139. if (!isset($element['#value'])) {
  1140. // Call #type_value without a second argument to request default_value
  1141. // handling.
  1142. $element['#value'] = call_user_func_array($value_callable, [&$element, FALSE, &$form_state]);
  1143. // Final catch. If we haven't set a value yet, use the explicit default
  1144. // value. Avoid image buttons (which come with garbage value), so we
  1145. // only get value for the button actually clicked.
  1146. if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
  1147. $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  1148. }
  1149. }
  1150. }
  1151. // Determine which element (if any) triggered the submission of the form and
  1152. // keep track of all the clickable buttons in the form for
  1153. // \Drupal\Core\Form\FormState::cleanValues(). Enforce the same input
  1154. // processing restrictions as above.
  1155. if ($process_input) {
  1156. // Detect if the element triggered the submission via Ajax.
  1157. if ($this->elementTriggeredScriptedSubmission($element, $form_state)) {
  1158. $form_state->setTriggeringElement($element);
  1159. }
  1160. // If the form was submitted by the browser rather than via Ajax, then it
  1161. // can only have been triggered by a button, and we need to determine
  1162. // which button within the constraints of how browsers provide this
  1163. // information.
  1164. if (!empty($element['#is_button'])) {
  1165. // All buttons in the form need to be tracked for
  1166. // \Drupal\Core\Form\FormState::cleanValues() and for the
  1167. // self::doBuildForm() code that handles a form submission containing no
  1168. // button information in \Drupal::request()->request.
  1169. $buttons = $form_state->getButtons();
  1170. $buttons[] = $element;
  1171. $form_state->setButtons($buttons);
  1172. if ($this->buttonWasClicked($element, $form_state)) {
  1173. $form_state->setTriggeringElement($element);
  1174. }
  1175. }
  1176. }
  1177. // Set the element's value in $form_state->getValues(), but only, if its key
  1178. // does not exist yet (a #value_callback may have already populated it).
  1179. if (!NestedArray::keyExists($form_state->getValues(), $element['#parents'])) {
  1180. $form_state->setValueForElement($element, $element['#value']);
  1181. }
  1182. }
  1183. /**
  1184. * Detects if an element triggered the form submission via Ajax.
  1185. *
  1186. * This detects button or non-button controls that trigger a form submission
  1187. * via Ajax or some other scriptable environment. These environments can set
  1188. * the special input key '_triggering_element_name' to identify the triggering
  1189. * element. If the name alone doesn't identify the element uniquely, the input
  1190. * key '_triggering_element_value' may also be set to require a match on
  1191. * element value. An example where this is needed is if there are several
  1192. * // buttons all named 'op', and only differing in their value.
  1193. */
  1194. protected function elementTriggeredScriptedSubmission($element, FormStateInterface &$form_state) {
  1195. $input = $form_state->getUserInput();
  1196. if (!empty($input['_triggering_element_name']) && $element['#name'] == $input['_triggering_element_name']) {
  1197. if (empty($input['_triggering_element_value']) || $input['_triggering_element_value'] == $element['#value']) {
  1198. return TRUE;
  1199. }
  1200. }
  1201. return FALSE;
  1202. }
  1203. /**
  1204. * Determines if a given button triggered the form submission.
  1205. *
  1206. * This detects button controls that trigger a form submission by being
  1207. * clicked and having the click processed by the browser rather than being
  1208. * captured by JavaScript. Essentially, it detects if the button's name and
  1209. * value are part of the POST data, but with extra code to deal with the
  1210. * convoluted way in which browsers submit data for image button clicks.
  1211. *
  1212. * This does not detect button clicks processed by Ajax (that is done in
  1213. * self::elementTriggeredScriptedSubmission()) and it does not detect form
  1214. * submissions from Internet Explorer in response to an ENTER key pressed in a
  1215. * textfield (self::doBuildForm() has extra code for that).
  1216. *
  1217. * Because this function contains only part of the logic needed to determine
  1218. * $form_state->getTriggeringElement(), it should not be called from anywhere
  1219. * other than within the Form API. Form validation and submit handlers needing
  1220. * to know which button was clicked should get that information from
  1221. * $form_state->getTriggeringElement().
  1222. */
  1223. protected function buttonWasClicked($element, FormStateInterface &$form_state) {
  1224. // First detect normal 'vanilla' button clicks. Traditionally, all standard
  1225. // buttons on a form share the same name (usually 'op'), and the specific
  1226. // return value is used to determine which was clicked. This ONLY works as
  1227. // long as $form['#name'] puts the value at the top level of the tree of
  1228. // \Drupal::request()->request data.
  1229. $input = $form_state->getUserInput();
  1230. // The input value attribute is treated as CDATA by browsers. This means
  1231. // that they replace character entities with characters. Therefore, we need
  1232. // to decode the value in $element['#value']. For more details see
  1233. // http://www.w3.org/TR/html401/types.html#type-cdata.
  1234. if (isset($input[$element['#name']]) && $input[$element['#name']] == Html::decodeEntities($element['#value'])) {
  1235. return TRUE;
  1236. }
  1237. // When image buttons are clicked, browsers do NOT pass the form element
  1238. // value in \Drupal::request()->Request. Instead they pass an integer
  1239. // representing the coordinates of the click on the button image. This means
  1240. // that image buttons MUST have unique $form['#name'] values, but the
  1241. // details of their \Drupal::request()->request data should be ignored.
  1242. elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
  1243. return TRUE;
  1244. }
  1245. return FALSE;
  1246. }
  1247. /**
  1248. * Wraps file_upload_max_size().
  1249. *
  1250. * @return string
  1251. * A translated string representation of the size of the file size limit
  1252. * based on the PHP upload_max_filesize and post_max_size.
  1253. */
  1254. protected function getFileUploadMaxSize() {
  1255. return file_upload_max_size();
  1256. }
  1257. /**
  1258. * Gets the current active user.
  1259. *
  1260. * @return \Drupal\Core\Session\AccountInterface
  1261. */
  1262. protected function currentUser() {
  1263. if (!$this->currentUser && \Drupal::hasService('current_user')) {
  1264. $this->currentUser = \Drupal::currentUser();
  1265. }
  1266. return $this->currentUser;
  1267. }
  1268. }