FormState.php 32.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\Core\Form\FormState.
 */

namespace Drupal\Core\Form;

10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Url;
12
use Symfony\Component\HttpFoundation\Response;
13 14 15 16

/**
 * Stores information about the state of a form.
 */
17
class FormState implements FormStateInterface {
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

  /**
   * Tracks if any errors have been set on any form.
   *
   * @var bool
   */
  protected static $anyErrors = FALSE;

  /**
   * The complete form structure.
   *
   * #process, #after_build, #element_validate, and other handlers being invoked
   * on a form element may use this reference to access other information in the
   * form the element is contained in.
   *
   * @see self::getCompleteForm()
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $complete_form;

  /**
   * An associative array of information stored by Form API that is necessary to
   * build and rebuild the form from cache when the original context may no
   * longer be available:
   *   - callback: The actual callback to be used to retrieve the form array.
   *     Can be any callable. If none is provided $form_id is used as the name
   *     of a function to call instead.
   *   - args: A list of arguments to pass to the form constructor.
   *   - files: An optional array defining include files that need to be loaded
   *     for building the form. Each array entry may be the path to a file or
   *     another array containing values for the parameters 'type', 'module' and
   *     'name' as needed by module_load_include(). The files listed here are
53 54
   *     automatically loaded by \Drupal::formBuilder()->getCache(). By default
   *     the current menu router item's 'file' definition is added, if any. Use
55
   *     self::loadInclude() to add include files from a form constructor.
56 57 58 59
   *   - form_id: Identification of the primary form being constructed and
   *     processed.
   *   - base_form_id: Identification for a base form, as declared in the form
   *     class's \Drupal\Core\Form\BaseFormIdInterface::getBaseFormId() method.
60 61 62 63 64 65
   *   - immutable: If this flag is set to TRUE, a new form build id is
   *     generated when the form is loaded from the cache. If it is subsequently
   *     saved to the cache again, it will have another cache id and therefore
   *     the original form and form-state will remain unaltered. This is
   *     important when page caching is enabled in order to prevent form state
   *     from leaking between anonymous users.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
   *
   * @var array
   */
  protected $build_info = array(
    'args' => array(),
    'files' => array(),
  );

  /**
   * Similar to self::$build_info, but pertaining to
   * \Drupal\Core\Form\FormBuilderInterface::rebuildForm().
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $rebuild_info = array();

  /**
   * Normally, after the entire form processing is completed and submit handlers
   * have run, a form is considered to be done and
   * \Drupal\Core\Form\FormSubmitterInterface::redirectForm() will redirect the
   * user to a new page using a GET request (so a browser refresh does not
   * re-submit the form). However, if 'rebuild' has been set to TRUE, then a new
   * copy of the form is immediately built and sent to the browser, instead of a
   * redirect. This is used for multi-step forms, such as wizards and
92 93 94 95 96 97
   * confirmation forms. Normally, self::$rebuild is set by a submit handler,
   * since its is usually logic within a submit handler that determines whether
   * a form is done or requires another step. However, a validation handler may
   * already set self::$rebuild to cause the form processing to bypass submit
   * handlers and rebuild the form instead, even if there are no validation
   * errors.
98 99 100 101 102 103 104 105 106 107 108 109 110
   *
   * This property is uncacheable.
   *
   * @see self::setRebuild()
   *
   * @var bool
   */
  protected $rebuild = FALSE;

  /**
   * Used when a form needs to return some kind of a
   * \Symfony\Component\HttpFoundation\Response object, e.g., a
   * \Symfony\Component\HttpFoundation\BinaryFileResponse when triggering a
111 112 113 114
   * file download. If you use self::setRedirect() or self::setRedirectUrl(),
   * it will be used to build a
   * \Symfony\Component\HttpFoundation\RedirectResponse and will populate this
   * key.
115 116 117 118 119 120
   *
   * @var \Symfony\Component\HttpFoundation\Response|null
   */
  protected $response;

  /**
121
   * Used to redirect the form on submission.
122
   *
123
   * @see self::getRedirect()
124 125 126
   *
   * This property is uncacheable.
   *
127
   * @var \Drupal\Core\Url|\Symfony\Component\HttpFoundation\RedirectResponse|null
128
   */
129
  protected $redirect;
130 131 132 133 134 135 136 137 138 139 140 141 142 143

  /**
   * If set to TRUE the form will NOT perform a redirect, even if
   * self::$redirect is set.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $no_redirect;

  /**
   * The HTTP form method to use for finding the input for this form.
   *
144
   * May be 'POST' or 'GET'. Defaults to 'POST'. Note that 'GET' method forms do
145
   * not use form ids so are always considered to be submitted, which can have
146 147
   * unexpected effects. The 'GET' method should only be used on forms that do
   * not change data, as that is exclusively the domain of 'POST.'
148 149 150 151 152
   *
   * This property is uncacheable.
   *
   * @var string
   */
153 154 155 156 157 158 159 160 161 162 163 164 165 166
  protected $method = 'POST';

  /**
   * The HTTP method used by the request building or processing this form.
   *
   * May be any valid HTTP method. Defaults to 'GET', because even though
   * $method is 'POST' for most forms, the form's initial build is usually
   * performed as part of a GET request.
   *
   * This property is uncacheable.
   *
   * @var string
   */
  protected $requestMethod = 'GET';
167 168 169 170 171 172 173 174 175 176 177

  /**
   * If set to TRUE the original, unprocessed form structure will be cached,
   * which allows the entire form to be rebuilt from cache. A typical form
   * workflow involves two page requests; first, a form is built and rendered
   * for the user to fill in. Then, the user fills the form in and submits it,
   * triggering a second page request in which the form must be built and
   * processed. By default, $form and $form_state are built from scratch during
   * each of these page requests. Often, it is necessary or desired to persist
   * the $form and $form_state variables from the initial page request to the
   * one that processes the submission. 'cache' can be set to TRUE to do this.
178 179
   * A prominent example is an Ajax-enabled form, in which
   * \Drupal\Core\Render\Element\RenderElement::processAjaxForm()
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
   * enables form caching for all forms that include an element with the #ajax
   * property. (The Ajax handler has no way to build the form itself, so must
   * rely on the cached version.) Note that the persistence of $form and
   * $form_state happens automatically for (multi-step) forms having the
   * self::$rebuild flag set, regardless of the value for self::$cache.
   *
   * @var bool
   */
  protected $cache = FALSE;

  /**
   * If set to TRUE the form will NOT be cached, even if 'cache' is set.
   *
   * @var bool
   */
  protected $no_cache;

  /**
   * An associative array of values submitted to the form.
   *
   * The validation functions and submit functions use this array for nearly all
   * their decision making. (Note that #tree determines whether the values are a
   * flat array or an array whose structure parallels the $form array. See the
   * @link forms_api_reference.html Form API reference @endlink for more
   * information.)
   *
   * This property is uncacheable.
   *
   * @var array
   */
210
  protected $values = array();
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  /**
   * An associative array of form value keys to be removed by cleanValues().
   *
   * Any values that are temporary but must still be displayed as values in
   * the rendered form should be added to this array using addCleanValueKey().
   * Initialized with internal Form API values.
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $cleanValueKeys = [
    'form_id',
    'form_token',
    'form_build_id',
    'op',
  ];

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
  /**
   * The array of values as they were submitted by the user.
   *
   * These are raw and unvalidated, so should not be used without a thorough
   * understanding of security implications. In almost all cases, code should
   * use the data in the 'values' array exclusively. The most common use of this
   * key is for multi-step forms that need to clear some of the user input when
   * setting 'rebuild'. The values correspond to \Drupal::request()->request or
   * \Drupal::request()->query, depending on the 'method' chosen.
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $input;

  /**
   * If TRUE and the method is GET, a form_id is not necessary.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $always_process;

  /**
   * Ordinarily, a form is only validated once, but there are times when a form
   * is resubmitted internally and should be validated again. Setting this to
   * TRUE will force that to happen. This is most likely to occur during Ajax
   * operations.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $must_validate;

  /**
   * If TRUE, the form was submitted programmatically, usually invoked via
   * \Drupal\Core\Form\FormBuilderInterface::submitForm(). Defaults to FALSE.
   *
   * @var bool
   */
  protected $programmed = FALSE;

  /**
   * If TRUE, programmatic form submissions are processed without taking #access
   * into account. Set this to FALSE when submitting a form programmatically
   * with values that may have been input by the user executing the current
   * request; this will cause #access to be respected as it would on a normal
   * form submission. Defaults to TRUE.
   *
   * @var bool
   */
  protected $programmed_bypass_access_check = TRUE;

  /**
   * TRUE signifies correct form submission. This is always TRUE for programmed
   * forms coming from \Drupal\Core\Form\FormBuilderInterface::submitForm() (see
   * 'programmed' key), or if the form_id coming from the
   * \Drupal::request()->request data is set and matches the current form_id.
   *
   * @var bool
   */
  protected $process_input;

  /**
   * If TRUE, the form has been submitted. Defaults to FALSE.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $submitted = FALSE;

  /**
   * If TRUE, the form was submitted and has been processed and executed.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $executed = FALSE;

  /**
   * The form element that triggered submission, which may or may not be a
   * button (in the case of Ajax forms). This key is often used to distinguish
   * between various buttons in a submit handler, and is also used in Ajax
   * handlers.
   *
   * This property is uncacheable.
   *
   * @var array|null
   */
  protected $triggering_element;

  /**
   * If TRUE, there is a file element and Form API will set the appropriate
   * 'enctype' HTML attribute on the form.
   *
   * @var bool
   */
  protected $has_file_element;

  /**
   * Contains references to details elements to render them within vertical tabs.
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $groups = array();

  /**
   *  This is not a special key, and no specific support is provided for it in
   *  the Form API. By tradition it was the location where application-specific
   *  data was stored for communication between the submit, validation, and form
   *  builder functions, especially in a multi-step-style form. Form
   *  implementations may use any key(s) within $form_state (other than the keys
   *  listed here and other reserved ones used by Form API internals) for this
   *  kind of storage. The recommended way to ensure that the chosen key doesn't
   *  conflict with ones used by the Form API or other modules is to use the
   *  module name as the key name or a prefix for the key name. For example, the
   *  entity form classes use $this->entity in entity forms, or
354
   *  $form_state->getFormObject()->getEntity() outside the controller, to store
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
   *  information about the entity being edited, and this information stays
   *  available across successive clicks of the "Preview" button (if available)
   *  as well as when the "Save" button is finally clicked.
   *
   * @var array
   */
  protected $storage = array();

  /**
   * A list containing copies of all submit and button elements in the form.
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $buttons = array();

  /**
   * Holds temporary data accessible during the current page request only.
   *
   * All $form_state properties that are not reserved keys (see
   * other properties marked as uncacheable) persist throughout a multistep form
   * sequence. Form API provides this key for modules to communicate information
   * across form-related functions during a single page request. It may be used
   * to temporarily save data that does not need to or should not be cached
   * during the whole form workflow; e.g., data that needs to be accessed during
   * the current form build process only. There is no use-case for this
   * functionality in Drupal core.
   *
   * This property is uncacheable.
   *
   * @var array
   */
388
  protected $temporary = [];
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

  /**
   * Tracks if the form has finished validation.
   *
   * This property is uncacheable.
   *
   * @var bool
   */
  protected $validation_complete = FALSE;

  /**
   * Contains errors for this form.
   *
   * This property is uncacheable.
   *
   * @var array
   */
  protected $errors = array();

  /**
   * Stores which errors should be limited during validation.
   *
411 412 413 414 415 416 417
   * An array of "sections" within which user input must be valid. If the
   * element is within one of these sections, the error must be recorded.
   * Otherwise, it can be suppressed. self::$limit_validation_errors can be an
   * empty array, in which case all errors are suppressed. For example, a
   * "Previous" button might want its submit action to be triggered even if none
   * of the submitted values are valid.
   *
418 419 420 421 422 423 424 425 426 427 428
   * This property is uncacheable.
   *
   * @var array|null
   */
  protected $limit_validation_errors;

  /**
   * Stores the gathered validation handlers.
   *
   * This property is uncacheable.
   *
429
   * @var array
430
   */
431
  protected $validate_handlers = [];
432 433 434 435 436 437

  /**
   * Stores the gathered submission handlers.
   *
   * This property is uncacheable.
   *
438
   * @var array
439
   */
440
  protected $submit_handlers = [];
441 442

  /**
443
   * {@inheritdoc}
444
   */
445 446 447 448 449 450 451 452 453 454
  public function setFormState(array $form_state_additions) {
    foreach ($form_state_additions as $key => $value) {
      if (property_exists($this, $key)) {
        $this->{$key} = $value;
      }
      else {
        $this->set($key, $value);
      }
    }
    return $this;
455 456 457 458 459
  }

  /**
   * {@inheritdoc}
   */
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  public function setAlwaysProcess($always_process = TRUE) {
    $this->always_process = (bool) $always_process;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getAlwaysProcess() {
    return $this->always_process;
  }

  /**
   * {@inheritdoc}
   */
  public function setButtons(array $buttons) {
    $this->buttons = $buttons;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return $this->buttons;
  }

  /**
   * {@inheritdoc}
   */
  public function setCached($cache = TRUE) {
491 492 493 494 495 496
    // Persisting $form_state is a side-effect disallowed during a "safe" HTTP
    // method.
    if ($cache && $this->isRequestMethodSafe()) {
      throw new \LogicException(sprintf('Form state caching on %s requests is not allowed.', $this->requestMethod));
    }

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    $this->cache = (bool) $cache;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isCached() {
    return empty($this->no_cache) && $this->cache;
  }

  /**
   * {@inheritdoc}
   */
  public function disableCache() {
    $this->no_cache = TRUE;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setExecuted() {
    $this->executed = TRUE;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isExecuted() {
    return $this->executed;
  }

  /**
   * {@inheritdoc}
   */
  public function setGroups(array $groups) {
    $this->groups = $groups;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function &getGroups() {
    return $this->groups;
  }

  /**
   * {@inheritdoc}
   */
  public function setHasFileElement($has_file_element = TRUE) {
    $this->has_file_element = (bool) $has_file_element;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function hasFileElement() {
    return $this->has_file_element;
  }

  /**
   * {@inheritdoc}
   */
  public function setLimitValidationErrors($limit_validation_errors) {
    $this->limit_validation_errors = $limit_validation_errors;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getLimitValidationErrors() {
    return $this->limit_validation_errors;
  }

  /**
   * {@inheritdoc}
   */
  public function setMethod($method) {
    $this->method = strtoupper($method);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isMethodType($method_type) {
    return $this->method === strtoupper($method_type);
  }

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  /**
   * {@inheritdoc}
   */
  public function setRequestMethod($method) {
    $this->requestMethod = strtoupper($method);
    return $this;
  }

  /**
   * Checks whether the request method is a "safe" HTTP method.
   *
   * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 defines
   * GET and HEAD as "safe" methods, meaning they SHOULD NOT have side-effects,
   * such as persisting $form_state changes.
   *
   * @return bool
   *
   * @see \Symfony\Component\HttpFoundation\Request::isMethodSafe()
   */
  protected function isRequestMethodSafe() {
    return in_array($this->requestMethod, array('GET', 'HEAD'));
  }

614 615 616 617 618
  /**
   * {@inheritdoc}
   */
  public function setValidationEnforced($must_validate = TRUE) {
    $this->must_validate = (bool) $must_validate;
619 620 621
    return $this;
  }

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
  /**
   * {@inheritdoc}
   */
  public function isValidationEnforced() {
    return $this->must_validate;
  }

  /**
   * {@inheritdoc}
   */
  public function disableRedirect($no_redirect = TRUE) {
    $this->no_redirect = (bool) $no_redirect;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isRedirectDisabled() {
   return $this->no_redirect;
  }

  /**
   * {@inheritdoc}
   */
  public function setProcessInput($process_input = TRUE) {
    $this->process_input = (bool) $process_input;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isProcessingInput() {
    return $this->process_input;
  }

  /**
   * {@inheritdoc}
   */
  public function setProgrammed($programmed = TRUE) {
    $this->programmed = (bool) $programmed;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isProgrammed() {
    return $this->programmed;
  }

  /**
   * {@inheritdoc}
   */
  public function setProgrammedBypassAccessCheck($programmed_bypass_access_check = TRUE) {
    $this->programmed_bypass_access_check = (bool) $programmed_bypass_access_check;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isBypassingProgrammedAccessChecks() {
    return $this->programmed_bypass_access_check;
  }

  /**
   * {@inheritdoc}
   */
  public function setRebuildInfo(array $rebuild_info) {
    $this->rebuild_info = $rebuild_info;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getRebuildInfo() {
    return $this->rebuild_info;
  }

  /**
   * {@inheritdoc}
   */
  public function addRebuildInfo($property, $value) {
    $rebuild_info = $this->getRebuildInfo();
    $rebuild_info[$property] = $value;
    $this->setRebuildInfo($rebuild_info);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setStorage(array $storage) {
    $this->storage = $storage;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function &getStorage() {
    return $this->storage;
  }

  /**
   * {@inheritdoc}
   */
  public function setSubmitHandlers(array $submit_handlers) {
    $this->submit_handlers = $submit_handlers;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getSubmitHandlers() {
    return $this->submit_handlers;
  }

  /**
   * {@inheritdoc}
   */
  public function setSubmitted() {
    $this->submitted = TRUE;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isSubmitted() {
    return $this->submitted;
  }

  /**
   * {@inheritdoc}
   */
  public function setTemporary(array $temporary) {
    $this->temporary = $temporary;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getTemporary() {
    return $this->temporary;
  }

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
  /**
   * {@inheritdoc}
   */
  public function &getTemporaryValue($key) {
    $value = &NestedArray::getValue($this->temporary, (array) $key);
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function setTemporaryValue($key, $value) {
    NestedArray::setValue($this->temporary, (array) $key, $value, TRUE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function hasTemporaryValue($key) {
    $exists = NULL;
    NestedArray::getValue($this->temporary, (array) $key, $exists);
    return $exists;
  }

799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  /**
   * {@inheritdoc}
   */
  public function setTriggeringElement($triggering_element) {
    $this->triggering_element = $triggering_element;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function &getTriggeringElement() {
    return $this->triggering_element;
  }

  /**
   * {@inheritdoc}
   */
  public function setValidateHandlers(array $validate_handlers) {
    $this->validate_handlers = $validate_handlers;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getValidateHandlers() {
    return $this->validate_handlers;
  }

  /**
   * {@inheritdoc}
   */
  public function setValidationComplete($validation_complete = TRUE) {
    $this->validation_complete = (bool) $validation_complete;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function isValidationComplete() {
    return $this->validation_complete;
  }

844 845 846 847 848 849 850
  /**
   * {@inheritdoc}
   */
  public function loadInclude($module, $type, $name = NULL) {
    if (!isset($name)) {
      $name = $module;
    }
851
    $build_info = $this->getBuildInfo();
852 853 854 855 856 857 858 859
    if (!isset($build_info['files']["$module:$name.$type"])) {
      // Only add successfully included files to the form state.
      if ($result = $this->moduleLoadInclude($module, $type, $name)) {
        $build_info['files']["$module:$name.$type"] = array(
          'type' => $type,
          'module' => $module,
          'name' => $name,
        );
860
        $this->setBuildInfo($build_info);
861 862 863 864 865 866
        return $result;
      }
    }
    return FALSE;
  }

867 868 869
  /**
   * {@inheritdoc}
   */
870 871 872 873 874 875 876 877 878 879 880
  public function getCacheableArray() {
    return [
      'build_info' => $this->getBuildInfo(),
      'response' => $this->getResponse(),
      'programmed' => $this->isProgrammed(),
      'programmed_bypass_access_check' => $this->isBypassingProgrammedAccessChecks(),
      'process_input' => $this->isProcessingInput(),
      'has_file_element' => $this->hasFileElement(),
      'storage' => $this->getStorage(),
      // Use the properties directly, since self::isCached() combines them and
      // cannot be relied upon.
881 882
      'cache' => $this->cache,
      'no_cache' => $this->no_cache,
883
    ];
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
  }

  /**
   * {@inheritdoc}
   */
  public function setCompleteForm(array &$complete_form) {
    $this->complete_form = &$complete_form;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function &getCompleteForm() {
    return $this->complete_form;
  }

  /**
   * {@inheritdoc}
   */
904 905 906 907 908 909 910 911 912 913
  public function &get($property) {
    $value = &NestedArray::getValue($this->storage, (array) $property);
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function set($property, $value) {
    NestedArray::setValue($this->storage, (array) $property, $value, TRUE);
914 915 916 917 918 919
    return $this;
  }

  /**
   * {@inheritdoc}
   */
920 921 922 923
  public function has($property) {
    $exists = NULL;
    NestedArray::getValue($this->storage, (array) $property, $exists);
    return $exists;
924 925 926 927 928
  }

  /**
   * {@inheritdoc}
   */
929 930
  public function setBuildInfo(array $build_info) {
    $this->build_info = $build_info;
931 932 933 934 935 936
    return $this;
  }

  /**
   * {@inheritdoc}
   */
937 938
  public function getBuildInfo() {
    return $this->build_info;
939 940 941 942 943 944
  }

  /**
   * {@inheritdoc}
   */
  public function addBuildInfo($property, $value) {
945
    $build_info = $this->getBuildInfo();
946
    $build_info[$property] = $value;
947
    $this->setBuildInfo($build_info);
948 949 950
    return $this;
  }

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  /**
   * {@inheritdoc}
   */
  public function &getUserInput() {
    return $this->input;
  }

  /**
   * {@inheritdoc}
   */
  public function setUserInput(array $user_input) {
    $this->input = $user_input;
    return $this;
  }

966 967 968
  /**
   * {@inheritdoc}
   */
969 970
  public function &getValues() {
    return $this->values;
971 972 973 974 975
  }

  /**
   * {@inheritdoc}
   */
976 977 978 979 980 981 982 983 984
  public function &getValue($key, $default = NULL) {
    $exists = NULL;
    $value = &NestedArray::getValue($this->getValues(), (array) $key, $exists);
    if (!$exists) {
      $value = $default;
    }
    return $value;
  }

985 986 987 988 989 990 991 992
  /**
   * {@inheritdoc}
   */
  public function setValues(array $values) {
    $this->values = $values;
    return $this;
  }

993 994 995 996 997
  /**
   * {@inheritdoc}
   */
  public function setValue($key, $value) {
    NestedArray::setValue($this->getValues(), (array) $key, $value, TRUE);
998 999 1000
    return $this;
  }

1001 1002 1003
  /**
   * {@inheritdoc}
   */
1004 1005
  public function unsetValue($key) {
    NestedArray::unsetValue($this->getValues(), (array) $key);
1006 1007 1008
    return $this;
  }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
  /**
   * {@inheritdoc}
   */
  public function hasValue($key) {
    $exists = NULL;
    $value = NestedArray::getValue($this->getValues(), (array) $key, $exists);
    return $exists && isset($value);
  }

  /**
   * {@inheritdoc}
   */
  public function isValueEmpty($key) {
    $exists = NULL;
    $value = NestedArray::getValue($this->getValues(), (array) $key, $exists);
    return !$exists || empty($value);
  }

  /**
   * {@inheritdoc}
   */
1030
  public function setValueForElement(array $element, $value) {
1031 1032 1033
    return $this->setValue($element['#parents'], $value);
  }

1034 1035 1036 1037
  /**
   * {@inheritdoc}
   */
  public function setResponse(Response $response) {
1038
    $this->response = $response;
1039 1040 1041
    return $this;
  }

1042 1043 1044 1045 1046 1047 1048
  /**
   * {@inheritdoc}
   */
  public function getResponse() {
    return $this->response;
  }

1049 1050 1051
  /**
   * {@inheritdoc}
   */
1052 1053 1054 1055 1056 1057 1058 1059 1060
  public function setRedirect($route_name, array $route_parameters = array(), array $options = array()) {
    $url = new Url($route_name, $route_parameters, $options);
    return $this->setRedirectUrl($url);
  }

  /**
   * {@inheritdoc}
   */
  public function setRedirectUrl(Url $url) {
1061
    $this->redirect = $url;
1062 1063 1064 1065 1066 1067 1068 1069 1070
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getRedirect() {
    // Skip redirection for form submissions invoked via
    // \Drupal\Core\Form\FormBuilderInterface::submitForm().
1071
    if ($this->isProgrammed()) {
1072 1073 1074
      return FALSE;
    }
    // Skip redirection if rebuild is activated.
1075
    if ($this->isRebuilding()) {
1076 1077 1078
      return FALSE;
    }
    // Skip redirection if it was explicitly disallowed.
1079
    if ($this->isRedirectDisabled()) {
1080 1081 1082
      return FALSE;
    }

1083
    return $this->redirect;
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  }

  /**
   * Sets the global status of errors.
   *
   * @param bool $errors
   *   TRUE if any form has any errors, FALSE otherwise.
   */
  protected static function setAnyErrors($errors = TRUE) {
    static::$anyErrors = $errors;
  }

  /**
   * {@inheritdoc}
   */
  public static function hasAnyErrors() {
    return static::$anyErrors;
  }

  /**
   * {@inheritdoc}
   */
  public function setErrorByName($name, $message = '') {
1107
    if ($this->isValidationComplete()) {
1108 1109 1110 1111 1112 1113
      throw new \LogicException('Form errors cannot be set after form validation has finished.');
    }

    $errors = $this->getErrors();
    if (!isset($errors[$name])) {
      $record = TRUE;
1114
      $limit_validation_errors = $this->getLimitValidationErrors();
1115 1116 1117 1118 1119 1120
      if ($limit_validation_errors !== NULL) {
        $record = FALSE;
        foreach ($limit_validation_errors as $section) {
          // Exploding by '][' reconstructs the element's #parents. If the
          // reconstructed #parents begin with the same keys as the specified
          // section, then the element's values are within the part of
1121 1122 1123 1124
          // $form_state->getValues() that the clicked button requires to be
          // valid, so errors for this element must be recorded. As the exploded
          // array will all be strings, we need to cast every value of the
          // section array to string.
1125 1126 1127 1128 1129 1130 1131 1132
          if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
            $record = TRUE;
            break;
          }
        }
      }
      if ($record) {
        $errors[$name] = $message;
1133
        $this->errors = $errors;
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
        static::setAnyErrors();
      }
    }

    return $this;
  }

  /**
   * {@inheritdoc}
   */
1144
  public function setError(array &$element, $message = '') {
1145 1146 1147 1148 1149 1150 1151 1152
    $this->setErrorByName(implode('][', $element['#parents']), $message);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function clearErrors() {
1153
    $this->errors = [];
1154 1155 1156 1157 1158 1159
    static::setAnyErrors(FALSE);
  }

  /**
   * {@inheritdoc}
   */
1160
  public function getError(array $element) {
1161
    if ($errors = $this->getErrors()) {
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
      $parents = array();
      foreach ($element['#parents'] as $parent) {
        $parents[] = $parent;
        $key = implode('][', $parents);
        if (isset($errors[$key])) {
          return $errors[$key];
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getErrors() {
1177
    return $this->errors;
1178 1179 1180 1181 1182 1183
  }

  /**
   * {@inheritdoc}
   */
  public function setRebuild($rebuild = TRUE) {
1184
    $this->rebuild = $rebuild;
1185 1186 1187
    return $this;
  }

1188 1189 1190 1191 1192 1193
  /**
   * {@inheritdoc}
   */
  public function isRebuilding() {
    return $this->rebuild;
  }
1194 1195 1196 1197 1198 1199

  /**
   * {@inheritdoc}
   */
  public function prepareCallback($callback) {
    if (is_string($callback) && substr($callback, 0, 2) == '::') {
1200
      $callback = [$this->getFormObject(), substr($callback, 2)];
1201 1202 1203 1204
    }
    return $callback;
  }

1205 1206 1207 1208 1209 1210 1211 1212
  /**
   * {@inheritdoc}
   */
  public function setFormObject(FormInterface $form_object) {
    $this->addBuildInfo('callback_object', $form_object);
    return $this;
  }

1213 1214 1215 1216
  /**
   * {@inheritdoc}
   */
  public function getFormObject() {
1217
    return $this->getBuildInfo()['callback_object'];
1218 1219
  }

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  /**
   * {@inheritdoc}
   */
  public function getCleanValueKeys() {
    return $this->cleanValueKeys;
  }

  /**
   * {@inheritdoc}
   */
  public function setCleanValueKeys(array $cleanValueKeys) {
    $this->cleanValueKeys = $cleanValueKeys;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function addCleanValueKey($cleanValueKey) {
    $keys = $this->getCleanValueKeys();
    $this->setCleanValueKeys(array_merge((array)$keys, [$cleanValueKey]));
    return $this;
  }

1244 1245 1246 1247
  /**
   * {@inheritdoc}
   */
  public function cleanValues() {
1248 1249 1250
    foreach ($this->getCleanValueKeys() as $value) {
      $this->unsetValue($value);
    }
1251 1252

    // Remove button values.
1253 1254
    // \Drupal::formBuilder()->doBuildForm() collects all button elements in a
    // form. We remove the button value separately for each button element.
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    foreach ($this->getButtons() as $button) {
      // Remove this button's value from the submitted form values by finding
      // the value corresponding to this button.
      // We iterate over the #parents of this button and move a reference to
      // each parent in self::getValues(). For example, if #parents is:
      //   array('foo', 'bar', 'baz')
      // then the corresponding self::getValues() part will look like this:
      // array(
      //   'foo' => array(
      //     'bar' => array(
      //       'baz' => 'button_value',
      //     ),
      //   ),
      // )
      // We start by (re)moving 'baz' to $last_parent, so we are able unset it
      // at the end of the iteration. Initially, $values will contain a
      // reference to self::getValues(), but in the iteration we move the
      // reference to self::getValue('foo'), and finally to
      // self::getValue(array('foo', 'bar')), which is the level where we
      // can unset 'baz' (that is stored in $last_parent).
      $parents = $button['#parents'];
      $last_parent = array_pop($parents);
      $key_exists = NULL;
      $values = &NestedArray::getValue($this->getValues(), $parents, $key_exists);
      if ($key_exists && is_array($values)) {
        unset($values[$last_parent]);
      }
    }
1283
    return $this;
1284 1285
  }

1286 1287 1288 1289 1290 1291 1292
  /**
   * Wraps ModuleHandler::loadInclude().
   */
  protected function moduleLoadInclude($module, $type, $name = NULL) {
    return \Drupal::moduleHandler()->loadInclude($module, $type, $name);
  }

1293
}