Add Remove Fields Dynamically using Form API and Ajax | Drupal 8

Add Remove Fields Dynamically using Form API and Ajax

Submitted by editor on Tue, 05/10/2016 - 14:03
Question

How th Add and/or Remove Fields Dynamically using Form API (FAPI) and Ajax on Drupal 8?

Example: Add/Remove 'test' Field depending on 'switch' field

1. on build()    
$form['test'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'edit-fields-test'],
    ];
    if ($form_state->getValue('switch') == 2) {
      $form['test'][0] = $this->getReturnTripFields($form, $form_state);
      $form['test'][0]['#prefix'] = '<div>';
      $form['test'][0]['#suffix'] = '</div>';
    }

    $form['switch'] = [
      '#type' => 'radios',
      '#title' => 'Trip Type',
      '#options' => [1 => 'NO', 2 => 'YES'],
      '#ajax' => array(
        'callback' => '::returnAjax',
        'wrapper' => 'edit-fields-test',
        'method' => 'replace',
      ),
    ];

2. AjaxMethode

  function returnAjax($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    if ($form_state->getValue('switch') == 2) {
      $content = [ '#markup' => ' YES ', ];
    }
    else {
      $content = [ '#markup' => ' ', ];
    }
    $response->addCommand(new HtmlCommand('#edit-fields-test', $content));
    return $response;
  }

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.