Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Add Remove Fields Dynamically using Form API and Ajax

By editor , 10 May, 2016
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;
  }

Tags

  • Drupal 8
  • Code
  • Form
Change the states of an element based on another element (field)
Increment or Decrement number of Fields Dynamically using Form API and Ajax

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer