Why does #triggering_element pick the wrong element? I'm triggering an ajax-enabled button on a form but Drupal's setting $form_state['#triggering_element'] to the wrong element.

The button is a child of a #tree and is identical to other buttons in other tree-ed structures, except for its parents. But I thought this was the point of #tree.

Looking at the drupal code in form.inc it's clear that Drupal only goes on the #name property to identify the triggering element, which is automatically set to 'op' for buttons. This seems to have no idea about trees or the element's parents.

The rather scant and very old docs for tree state:


  #parents is used to create the name/ID of the form element itself.


But my button element's names are not being set to anything other than 'op'. I'm creating the buttons in a #process function for the parent element.

Example code

$form['group1'] = [
  '#prefix' =&gt; '&lt;div&gt;group1',
  '#suffix' =&gt; '&lt;/div&gt;',
  '#tree' =&gt; TRUE,
  'trig' =&gt; [
    '#type' =&gt; 'submit',
    '#value' =&gt; 'ajax go',
    '#ajax' =&gt; [
      'callback' =&gt; 'mymod_ajax_callback',
      'wrapper' =&gt; 'foo',
      ],
  // Other elements part of group 1...
  ],
$form['group2'] = // The same.


A work-around is to code creating unique names for every one of these elements, but I feel I might be missing a trick/nuance?
The problem is in form_builder() where it fallbacks to the first button if no button can be found. 

A comment from form_builder():

// Therefore, to be as consistent as we
// can be across browsers, if no 'triggering_element' has been identified
// yet, default it to the first button.
if (!$form_state['programmed'] &amp;&amp; !isset($form_state['triggering_element']) &amp;&amp; !empty($form_state['buttons'])) {
  $form_state['triggering_element'] = $form_state['buttons'][0];
}


More info can be found here: https://www.drupal.org/node/2546700#comment-11164091

There is also a patch for this problem that can be found in the link above.