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

Ajax Form

By editor , 18 November, 2015
Question

How to Change a form using ajax ?

Exemple : Field 'username'

//Form
    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => 'Your user name',
      '#description' => 'User name',
      '#ajax' => array(
        'callback' => '::checkUserNameAjax',
        'wrapper' => 'edit-username',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'change',
      ),

      //If you want to change the ID
      '#prefix' => '<div id="edit-username">',
      '#suffix' => '</div>',
    );

1. Ajax Methode to Edit Form
  function checkUserNameAjax($form, FormStateInterface $form_state) {
    $form['username']['#description'] = "YES";
    return $form['username'];
  }

2. Or using AjaxResponse to change HTML/CSS

  function checkUserNameAjax(array &$form, FormStateInterface &$form_state) {
    $valid = rand(0,1);
    if ($valid) {
      $css = ['border' => '1px solid green'];
      $message = ('User name ok.');
    }else {
      $css = ['border' => '1px solid red'];
      $message = ('User name not valid.');
    }
    $response = new \Drupal\Core\Ajax\AjaxResponse();
    $response->addCommand(new \Drupal\Core\Ajax\CssCommand('#edit-username', $css));
    $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('#edit-username--description', $message));
    return $response;
  }

Example 2 : Change a title using selected value

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['methods'] = array(
    '#type' => 'select',
    '#title' => $this->t('Method'),
    '#default_value' => "",
    '#options' => ["a"=>"A Value","b"=>"B Value",],
    '#ajax' => array(
      'callback' => '::methodChangeAjax',
      'wrapper' => 'edit-fieldsset',
      'method' => 'replace',
      'effect' => 'fade',
      'event' => 'change',
    ),
  );
//Ajax changable fields container
  $form['fieldsset'] = array(
    '#type' => 'fieldset',
    '#title' => $this->t('Fields'),
    '#default_value' => "",
    '#prefix' => '<div id="edit-fieldsset">',
    '#suffix' => '</div>',
  );
  return $form;
}
function methodChangeAjax($form, FormStateInterface $form_state) {
  $method = $form_state->getValue('methods');
  $form['fieldsset']['#title'] = $method;
  return $form['fieldsset'];
}

Tags

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

Comments4

Plain text

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

rakesh.gectcr (not verified)

10 years 7 months ago

I am not able to to get the field values in form submit

Drupal 8 , I have added new text field through ajax, When the form submit in the $form_state not having  respective field value 

  • Reply

Pryrios (not verified)

9 years 5 months ago

In reply to I am not able to to get the field values in form submit by rakesh.gectcr (not verified)

Just for the sake of helping whoever gets here

This happens if you add the fields on the callback function. The form doesn't get rebuilt at this point, so the values on the new fields are discarded. You need to add the fields on buildForm function by checking on the $form_state values.

On the simplest case, you can check that the triggering field has a value set and then conditionally build the new field as per defined functionality. Then on the callback you just need to call:

$form_state->setRebuild(true);
return $form['wrapper_of_the_element_to_change'];

  • Reply

kamal (not verified)

9 years ago

Drupal 8.4

That's not working with Drupal 8.4

  • Reply

WillBradley (not verified)

8 years 4 months ago

RE:Ajax Form

As a rule, there are two different ways to AJAX this form submit! That is, we present the form via AJAX and the server returns HTML. The AJAX would restore the form HTML with the blunder in it so we can render it on the page assignment help service. This is less demanding... since you don't have to do all that much in JavaScript. Be that as it may, this approach is also a bit outdated.

  • Reply

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