You are here

public function FormBuilder::retrieveForm in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Form/FormBuilder.php \Drupal\Core\Form\FormBuilder::retrieveForm()
  2. 9 core/lib/Drupal/Core/Form/FormBuilder.php \Drupal\Core\Form\FormBuilder::retrieveForm()

File

core/lib/Drupal/Core/Form/FormBuilder.php, line 504

Class

FormBuilder
Provides form building and processing.

Namespace

Drupal\Core\Form

Code

public function retrieveForm($form_id, FormStateInterface &$form_state) {

  // Record the $form_id.
  $form_state
    ->addBuildInfo('form_id', $form_id);

  // We save two copies of the incoming arguments: one for modules to use
  // when mapping form ids to constructor functions, and another to pass to
  // the constructor function itself.
  $build_info = $form_state
    ->getBuildInfo();
  $args = $build_info['args'];
  $callback = [
    $form_state
      ->getFormObject(),
    'buildForm',
  ];
  $form = [];

  // Assign a default CSS class name based on $form_id.
  // This happens here and not in self::prepareForm() in order to allow the
  // form constructor function to override or remove the default class.
  $form['#attributes']['class'][] = Html::getClass($form_id);

  // Same for the base form ID, if any.
  if (isset($build_info['base_form_id'])) {
    $form['#attributes']['class'][] = Html::getClass($build_info['base_form_id']);
  }

  // We need to pass $form_state by reference in order for forms to modify it,
  // since call_user_func_array() requires that referenced variables are
  // passed explicitly.
  $args = array_merge([
    $form,
    &$form_state,
  ], $args);
  $form = call_user_func_array($callback, $args);

  // If the form returns a response, skip subsequent page construction by
  // throwing an exception.
  // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber
  //
  // @todo Exceptions should not be used for code flow control. However, the
  //   Form API currently allows any form builder functions to return a
  //   response.
  //   @see https://www.drupal.org/node/2363189
  if ($form instanceof Response) {
    throw new EnforcedResponseException($form);
  }
  $form['#form_id'] = $form_id;
  return $form;
}