You are here

protected function FormBuilder::buttonWasClicked in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Form/FormBuilder.php \Drupal\Core\Form\FormBuilder::buttonWasClicked()
  2. 10 core/lib/Drupal/Core/Form/FormBuilder.php \Drupal\Core\Form\FormBuilder::buttonWasClicked()

Determines if a given button triggered the form submission.

This detects button controls that trigger a form submission by being clicked and having the click processed by the browser rather than being captured by JavaScript. Essentially, it detects if the button's name and value are part of the POST data, but with extra code to deal with the convoluted way in which browsers submit data for image button clicks.

This does not detect button clicks processed by Ajax (that is done in self::elementTriggeredScriptedSubmission()) and it does not detect form submissions from Internet Explorer in response to an ENTER key pressed in a textfield (self::doBuildForm() has extra code for that).

Because this function contains only part of the logic needed to determine $form_state->getTriggeringElement(), it should not be called from anywhere other than within the Form API. Form validation and submit handlers needing to know which button was clicked should get that information from $form_state->getTriggeringElement().

1 call to FormBuilder::buttonWasClicked()
FormBuilder::handleInputElement in core/lib/Drupal/Core/Form/FormBuilder.php
Adds the #name and #value properties of an input element before rendering.

File

core/lib/Drupal/Core/Form/FormBuilder.php, line 1364

Class

FormBuilder
Provides form building and processing.

Namespace

Drupal\Core\Form

Code

protected function buttonWasClicked($element, FormStateInterface &$form_state) {

  // First detect normal 'vanilla' button clicks. Traditionally, all standard
  // buttons on a form share the same name (usually 'op'), and the specific
  // return value is used to determine which was clicked. This ONLY works as
  // long as $form['#name'] puts the value at the top level of the tree of
  // \Drupal::request()->request data.
  $input = $form_state
    ->getUserInput();

  // The input value attribute is treated as CDATA by browsers. This means
  // that they replace character entities with characters. Therefore, we need
  // to decode the value in $element['#value']. For more details see
  // http://www.w3.org/TR/html401/types.html#type-cdata.
  if (isset($input[$element['#name']]) && $input[$element['#name']] == Html::decodeEntities($element['#value'])) {
    return TRUE;
  }
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
    return TRUE;
  }
  return FALSE;
}