Score:1

AJAX callback is fired only once

eg flag

I am using hook_form_alter() hook to add an Apply button to the node edit form.. When users click on that button, an AJAX callback replaces the text field value.

It works fine the first time, but the second time it doesn't replace the value.

function course_form_node_items_edit_form_alter(&$form, FormStateInterface $form_state) {

  $form['apply'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#weight' => '38',
    '#executes_submit_callback' => FALSE,
    '#limit_validation_errors' => array(),
    '#ajax' => array(
      'callback' => 'button_test_callback',
      'wrapper' => 'edit-field-text-plain-0-value',
    ),
  );
}
    
function button_test_callback(&$form, FormStateInterface $form_state) {
  $item_id = $form['field_item_id']['widget'][0]['value']['#value'];
  $sql = "SELECT  item_name
          FROM items
          WHERE  field_item_id = '" . $item_id . "'";
    
  $location = \Drupal::database()->query($sql)->fetchAssoc();
    
  $form['field_text_plain']['widget'][0]['value']['#value'] = $location;
 $form['field_text_plain']['widget']['0']['value']['#id'] = 'edit-field-text-plain-0-value';
  return $form['field_text_plain'];
}

After the first click, the form_text_plain ID changes to some random value, for example edit-field-text-plain-0-value-xhfjwos. It seems that is the issue.

Is there any way to avoid the form_text_plain ID changes?

Jaypan avatar
de flag
I'm guessing the wrapper ID changes when it is first replaced. It's not shown where that wrapper ID comes from though, so that's speculation.
vyshnavi avatar
eg flag
@Jaypan now i am able to change the id of the wrapper , but it looks like the real issue is the callback is not getting the updated user form field input when the user enters the item id value second time , is there anyway to get that updated form field value to the call back ?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.