0

I have a form containing a table, which displays rows from a database table, and has a couple of editable fields, which is all working fine.

I now want to make one of fields trigger an AJAX callback when changed, and the callback to update another field in the same row.

Can the callback function check which instance of the changed field triggered the callback, so it knows which row to update?

Thanks for your help, and happy new year!

James

1
  • 1
    No, this is a long standing "bug" of Drupal when it comes to ajax. To avoid mismatching IDs I always put the ID int the button name and extract it in the submit handler. For example set the #name => 'dosomething__23' on the ajax button and in submit handler extract via substr($form_state->getTriggeringElement()['#name'], strlen('dosomething__')).
    – user21641
    Commented Dec 31, 2015 at 14:43

1 Answer 1

2

I use this code since drupal 7, only changed the first line for drupal 8:

$triggering_element = $form_state->getTriggeringElement();
if ( isset($triggering_element) ) {
  $trigger = $triggering_element['#name'];
  if ( $trigger == 'op' ) {
    $trigger = $triggering_element['#parents']['0'];
  }
}
else {
  $trigger = '';
};

If trigger is 'op', then it is a button and i get the name from the parent.

And see comment of Ivan Jaros, make the names unique.

2
  • Thanks, this is very helpful. My control is a #checkbox on a #table, so I thought I might have to give each checkbox a unique #name to tell them apart. However $triggering_element['#name'] returns table[98][is_approved], so that should be perfect for my needs! Commented Jan 1, 2016 at 14:05
  • I'm still having a couple of problems, but I think this question has been answered. Commented Jan 1, 2016 at 15:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.