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?

  • 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.
    – Jaypan
    Commented Aug 28, 2021 at 7:34
  • @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 ?
    – vyshnavi
    Commented Aug 28, 2021 at 14:39


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.