3 namespace Drupal\form_test\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Form builder to test button click detection.
13 class FormTestClickedButtonForm extends FormBase {
18 public function getFormId() {
19 return 'form_test_clicked_button';
25 public function buildForm(array $form, FormStateInterface $form_state, $first = NULL, $second = NULL, $third = NULL) {
26 // A single text field. In IE, when a form has only one non-button input field
27 // and the ENTER key is pressed while that field has focus, the form is
28 // submitted without any information identifying the button responsible for
29 // the submission. In other browsers, the form is submitted as though the
30 // first button were clicked.
33 '#type' => 'textfield',
36 // Loop through each path argument, adding buttons based on the information
37 // in the argument. For example, if the path is
38 // form-test/clicked-button/s/i/rb, then 3 buttons are added: a 'submit', an
39 // 'image_button', and a 'button' with #access=FALSE. This enables form.test
40 // to test a variety of combinations.
42 $args = [$first, $second, $third];
43 foreach ($args as $arg) {
44 $name = 'button' . ++$i;
45 // 's', 'b', or 'i' in the argument define the button type wanted.
46 if (strpos($arg, 's') !== FALSE) {
49 elseif (strpos($arg, 'b') !== FALSE) {
52 elseif (strpos($arg, 'i') !== FALSE) {
53 $type = 'image_button';
63 // Image buttons need a #src; the others need a #value.
64 if ($type == 'image_button') {
65 $form[$name]['#src'] = 'core/misc/druplicon.png';
68 $form[$name]['#value'] = $name;
70 // 'r' for restricted, so we can test that button click detection code
71 // correctly takes #access security into account.
72 if (strpos($arg, 'r') !== FALSE) {
73 $form[$name]['#access'] = FALSE;
84 public function validateForm(array &$form, FormStateInterface $form_state) {
85 if ($triggering_element = $form_state->getTriggeringElement()) {
86 $this->messenger()->addStatus(t('The clicked button is %name.', ['%name' => $triggering_element['#name']]));
89 $this->messenger()->addStatus('There is no clicked button.');
96 public function submitForm(array &$form, FormStateInterface $form_state) {
97 $this->messenger()->addStatus('Submit handler for form_test_clicked_button executed.');