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;
  }
Comments