简体   繁体   English

如何获取Drupal 8 Form中的触发按钮id

[英]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.您好,我想知道一种获取在 Drupal 8 表单中单击的按钮的索引 ID 的方法。 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 和 Drupal 7 中实现,但无法在 Drupal 8 中实现。

Drupal 6: Drupal 6:

function field_add($form, &$form_state) {

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

Drupal 7: Drupal 7:

function field_add($form, &$form_state) {

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

How to get the same in Drupal 8?如何在 Drupal 8 中得到相同的值?

I was able to Figure it . 我能够弄清楚。 Here is a way to achieve it in Drupal 8. 这是在Drupal 8中实现的一种方法。

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

在Drupal 8中,这对我而言有效

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

In Drupal 8 I named my button using attribute "#name" to be able to use this code: 在Drupal 8中,我使用属性“ #name”为按钮命名,以便能够使用以下代码:

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

By this way you prevent a possible issue with the array index being different. 通过这种方式,可以防止数组索引不同而可能出现的问题。

In Drupal 9 this worked for me在 Drupal 9 这对我有用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM