You are here

public function MultistepForm::buildForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/form_api_example/src/Form/MultistepForm.php \Drupal\form_api_example\Form\MultistepForm::buildForm()

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides FormInterface::buildForm

File

form_api_example/src/Form/MultistepForm.php, line 28

Class

MultistepForm
Provides a form with two steps.

Namespace

Drupal\form_api_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  if ($form_state
    ->has('page_num') && $form_state
    ->get('page_num') == 2) {
    return self::fapiExamplePageTwo($form, $form_state);
  }
  $form_state
    ->set('page_num', 1);
  $form['description'] = [
    '#type' => 'item',
    '#title' => $this
      ->t('A basic multistep form (page 1)'),
  ];
  $form['first_name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('First Name'),
    '#description' => $this
      ->t('Enter your first name.'),
    '#default_value' => $form_state
      ->getValue('first_name', ''),
    '#required' => TRUE,
  ];
  $form['last_name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Last Name'),
    '#default_value' => $form_state
      ->getValue('last_name', ''),
    '#description' => $this
      ->t('Enter your last name.'),
  ];
  $form['birth_year'] = [
    '#type' => 'number',
    '#title' => $this
      ->t('Birth Year'),
    '#default_value' => $form_state
      ->getValue('birth_year', ''),
    '#description' => $this
      ->t('Format is "YYYY" and value between 1900 and 2000'),
  ];

  // Group submit handlers in an actions element with a key of "actions" so
  // that it gets styled correctly, and so that other modules may add actions
  // to the form. This is not required, but is convention.
  $form['actions'] = [
    '#type' => 'actions',
  ];
  $form['actions']['next'] = [
    '#type' => 'submit',
    '#button_type' => 'primary',
    '#value' => $this
      ->t('Next'),
    // Custom submission handler for page 1.
    '#submit' => [
      '::fapiExampleMultistepFormNextSubmit',
    ],
    // Custom validation handler for page 1.
    '#validate' => [
      '::fapiExampleMultistepFormNextValidate',
    ],
  ];
  return $form;
}