You are here

public function AjaxColorForm::buildForm in Examples for Developers 3.x

Same name and namespace in other branches
  1. 8 form_api_example/src/Form/AjaxColorForm.php \Drupal\form_api_example\Form\AjaxColorForm::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

modules/form_api_example/src/Form/AjaxColorForm.php, line 29

Class

AjaxColorForm
Implements the ajax demo form controller.

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 functioning of an AJAX callback.'),
  ];

  // The #ajax attribute used in the temperature input element defines an ajax
  // callback that will invoke the 'updateColor' method on this form object.
  // Whenever the temperature element changes, it will invoke this callback
  // and replace the contents of the 'color_wrapper' container with the
  // results of this method call.
  $form['temperature'] = [
    '#title' => $this
      ->t('Temperature'),
    '#type' => 'select',
    '#options' => $this
      ->getColorTemperatures(),
    '#empty_option' => $this
      ->t('- Select a color temperature -'),
    '#ajax' => [
      // Could also use [get_class($this), 'updateColor'].
      'callback' => '::updateColor',
      'wrapper' => 'color-wrapper',
    ],
  ];

  // Add a wrapper that can be replaced with new HTML by the ajax callback.
  // This is given the ID that was passed to the ajax callback in the '#ajax'
  // element above.
  $form['color_wrapper'] = [
    '#type' => 'container',
    '#attributes' => [
      'id' => 'color-wrapper',
    ],
  ];

  // Add a color element to the color_wrapper container using the value
  // from temperature to determine which colors to include in the select
  // element.
  $temperature = $form_state
    ->getValue('temperature');
  if (!empty($temperature)) {
    $form['color_wrapper']['color'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Color'),
      '#options' => $this
        ->getColorsByTemperature($temperature),
    ];
  }

  // Add a submit button that handles the submission of the form.
  $form['actions'] = [
    '#type' => 'actions',
    'submit' => [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ],
  ];
  return $form;
}