phpdrupaldrupal-7drupal-6drupal-8

How to get triggered button id in Drupal 8 Form


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 ?


Solution

  • 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];
    }