FormBuilder.php 60 KB

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