I try to create a form with two submit buttons and each button will use a different function: the default submitForm
function and a custom submitFormEndSession
function. So I have this code:
class EndSessionForm extends FormBase {
/**
* @var \Drupal
*/
private $drupal;
public function __construct() {
$this->drupal = new Drupal();
}
/**
* {@inheritdoc}
*/
public function getFormId(): string {
return 'end_session_form';
}
public function buildForm(array $form, FormStateInterface $form_state): array {
// ... some fields
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Close the session',
'#name' => 'btnEnd',
];
$form['stop'] = [
'#type' => 'submit',
'#value' => 'Stop the session',
'#name' => 'btnStop',
];
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// Function to call with the btnEnd button
}
public function submitStopForm(array &$form, FormStateInterface $form_state) {
// Function to call with the btnStop button
}
}
According to the documentation of Drupal 9.2.x, the only thing I had to do is add a #submit
parameter to the $form['stop']
element like this:
$form['stop'] = [
'#type' => 'submit',
'#value' => 'Stop the session',
'#name' => 'btnStop',
'#submit' => [ $this, 'submitStopForm' ] // link to the second submit function
]
But it doesn't work.
After many tries and researches, I've found a partial solution by adding this in buildForm
:
$form['#submit'][] = [$this, 'submitStopForm'];
The two buttons are now linked to submitForm
and submitStopForm
, no matter if I put a #submit
parameter on the buttons or not, submitStopForm
is executed first then submitForm
. But I'm wonder how I can link the first button to submitForm
and the second one to submitStopForm
properly and without enter in both functions when we click on one button.
Thanks and have a nice day!