Drupal - How to get triggering_element
Eyal is correct. FormState has a method getTriggeringElement. See the original change record for details.
$form_state->getTriggeringElement();
and if you want to get id try
$triggerdElement = $form_state->getTriggeringElement();
$htmlIdofTriggeredElement = $triggerdElement['#id'];
My preferred method is:
$triggering_element = $form_state->getTriggeringElement();
$button_name = $triggering_element['#name'];
if ($button_name === 'button1') {
// ...
}
Works both for validateForm() and submitForm().
Ensure you have #name for all your buttons. E.g.:
$form['button1'] = [
'#type' => 'submit',
'#name' => 'button1',
'#value' => $this->t('Button 1'),
];
Compared to $triggering_element['#id'] it's more stable because #id auto-generated and can change implicitly.
Compared to $triggering_element['#value'] it's better because:
- #value can be not unique;
- #value is a part UI (button label) and frequently changes.