You are here

public function ContainerDemo::buildForm in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/form_api_example/src/Form/ContainerDemo.php \Drupal\form_api_example\Form\ContainerDemo::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/ContainerDemo.php, line 22

Class

ContainerDemo
Implements the container demo form.

Namespace

Drupal\form_api_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['description'] = [
    '#type' => 'item',
    '#markup' => $this
      ->t('This form example demonstrates container elements: details, fieldset and container.'),
  ];

  // Details containers replace D7's collapsible field sets.
  $form['author'] = [
    '#type' => 'details',
    '#title' => 'Author Info (type = details)',
  ];
  $form['author']['name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Name'),
  ];
  $form['author']['pen_name'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Pen Name'),
  ];

  // Conventional field set.
  $form['book'] = [
    '#type' => 'fieldset',
    '#title' => $this
      ->t('Book Info (type = fieldset)'),
  ];
  $form['book']['title'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Title'),
  ];
  $form['book']['publisher'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Publisher'),
  ];

  // Containers have no visual display but wrap any contained elements in a
  // div tag.
  $form['accommodation'] = [
    '#type' => 'container',
  ];
  $form['accommodation']['title'] = [
    '#type' => 'html_tag',
    '#tag' => 'p',
    '#value' => $this
      ->t('Special Accommodations (type = container)'),
  ];
  $form['accommodation']['diet'] = [
    '#type' => 'textfield',
    '#title' => $this
      ->t('Dietary Restrictions'),
  ];
  $form['actions'] = [
    '#type' => 'actions',
  ];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $this
      ->t('Submit'),
  ];
  return $form;
}