How to get triggered button id in Drupal 8 Form

3.9k Views Asked by At

Hi I would like to know a way to get the index id of the button clicked in Drupal 8 form. I have a form withe some fields. It has Add, Remove,Add More buttons.

I want to remove the value of the particular field when I click on remove button. In order to do so I need to know the index of the clicked button . I was able to achieve that in Drupal 6 and Drupal 7 But cant achieve that in Drupal 8.

Drupal 6:

function field_add($form, &$form_state) {

  $element_key = $form_state['clicked_button']['#parents'][1];
}

Drupal 7:

function field_add($form, &$form_state) {

  $element_key = $form_state['triggering_element']['#parents'][1];
}

How to get the same in Drupal 8 ?

4

There are 4 best solutions below

1
miststudent2011 On BEST ANSWER

I was able to Figure it . Here is a way to achieve it in Drupal 8.

public function field_add(array &$form, FormStateInterface $form_state) {
    $element_key = $form_state->getTriggeringElement()['#parents'][1];
}
0
Md Eqbal Ahmad On

In Drupal 8 this has worked in my case

$clickedElement = $form_state->getTriggeringElement()['#array_parents'][1];
1
Michel Settembrino On

In Drupal 8 I named my button using attribute "#name" to be able to use this code:

$clickedElement = $form_state->getTriggeringElement()['#name'];

By this way you prevent a possible issue with the array index being different.

0
Gilbert M. On

In Drupal 9 this worked for me

$form_state->getUserInput()['_triggering_element_name'];