Ajax Form | Drupal 8

Ajax Form

Submitted by editor on Wed, 11/18/2015 - 16:48
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'];
}

Comments

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'];

WillBradley (not verified)

Tue, 07/17/2018 - 14:36

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.

Omprakash Mankar (not verified)

Sat, 08/29/2020 - 19:27

I have created a custom module in this custom form I have use radio button on click on radio button change fields you can see in the share screenshot but once click on radio button I get given selected field but when I submit one entry and then I want to edit the same form that select type field already selected but want given field are not render I mean field is hidden.hope you understand my question and explanation ajax callback is not working in on my edit form. let me know if you any other questions.i am sharing my module code link to better understand

https://github.com/omrmankar/json_file_data/tree/master/json_file_data

above is my module code

https://github.com/omrmankar/json_file_data/blob/master/json_file_data/… (this my form code for better understand)

Thanks in advance !!!

Umair Riaz (not verified)

Tue, 11/10/2020 - 12:40

I have made a custom module in this custom structure I have utilize radio catch on click on radio catch change fields you can find in the offer screen capture yet once click on radio catch I get given chosen field yet when I submit one passage and afterward I need to alter a similar structure that select kind field previously chose however need given field are not render I mean field is hidden.hope you comprehend my inquiry and clarification ajax callback isn't working in on my alter structure. inform me as to whether you some other questions.i am sharing my module code connect to more readily comprehend. https://www.ditrc.com/

Add new comment

Plain text

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