When a form is submitted, FormBuilder figures out which element in the form caused the submission -- this can be any kind of element, but often will be a button.
In the case of an AJAX submission, elementTriggeredScriptedSubmission() is the method that does the work. It checks each element of the form to see whether it matches the data in the input.
It does this by comparing in order:
- the element #name against $form_state->getUserInput()['_triggering_element_name']
- the element #value against $form_state->getUserInput()['_triggering_element_value']
For buttons, #name is nearly always 'op', because that's what buttons usually get as a name (this seems to be the default if you don't set it explicitly, but I don't see where FormAPI does that). The docs in FormAPI say this too:
// First detect normal 'vanilla' button clicks. Traditionally, all standard
// buttons on a form share the same name (usually 'op'), and the specific
This means that if you have two AJAX buttons on the form that don't set #name, and that have the same label, then FormAPI will call this for each one it finds, and the last one will win as the triggering element.
The solution is to set #name explicitly. The Field system does this, because in a typical entity form there might be several 'Add another item' button:
$elements['add_more'] = [
'#type' => 'submit',
'#name' => strtr($id_prefix, '-', '_') . '_add_more',
'#value' => t('Add another item'),
However, the #name property is not documented much (see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21...)
As well as documenting this, I suggest that FormState::setTriggeringElement() throw an exception if called more than once.
Apart from elementTriggeredScriptedSubmission() calling this successively, I don't think this should normally be called more than once.
| Comment | File | Size | Author |
|---|---|---|---|
| #3 | 2943055.3.core_.setTriggeringElement-throw-exception-if-set.patch | 617 bytes | joachim |
Comments
Comment #2
joachim commentedComment #3
joachim commentedLet's see if this breaks anything!
Comment #13
smustgrave commentedThis came up as the daily BSI target
Tagging for summary update to adopt to the issue template.
Will also need test coverage.
Change itself seems pretty simple and still applies