You are here

public function SessionExampleForm::buildForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/session_example/src/Form/SessionExampleForm.php \Drupal\session_example\Form\SessionExampleForm::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

session_example/src/Form/SessionExampleForm.php, line 75

Class

SessionExampleForm
Form to allow the user to store information in their session.

Namespace

Drupal\session_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['description'] = [
    '#type' => 'item',
    '#title' => $this
      ->t('Session Data Form'),
    '#markup' => $this
      ->t('In this example form, data that you enter into the form will be saved into your session data, which persists until you log out of Drupal.'),
  ];
  $form['name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Name'),
    '#placeholder' => $this
      ->t('Your name.'),
    '#default_value' => $this->session
      ->get('session_example.name', ''),
  ];
  $form['email'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Email'),
    '#placeholder' => $this
      ->t('Your email address.'),
    '#default_value' => $this->session
      ->get('session_example.email', ''),
  ];
  $form['quest'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Quest'),
    '#placeholder' => $this
      ->t('What is your quest?'),
    '#default_value' => $this->session
      ->get('session_example.quest', ''),
  ];
  $form['color'] = [
    '#type' => 'select',
    '#title' => $this
      ->t('Favorite Color'),
    '#options' => [
      '' => $this
        ->t('--'),
      'red' => $this
        ->t('Red'),
      'blue' => $this
        ->t('Blue'),
      'yellow' => $this
        ->t('Yellow'),
      'argggh' => $this
        ->t('Argggghhh!!'),
    ],
    '#default_value' => $this->session
      ->get('session_example.color', ''),
    '#description' => $this
      ->t('What is your favorite color?'),
  ];
  $form['save'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Save'),
  ];
  $form['reset'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Clear Session'),
    '#submit' => [
      '::submitClearSession',
    ],
  ];
  return $form;
}