I'm often using Drupal::messenger()
to show status/warning messages before I submit the form. But those messages are usually counter-intuitive once the form has been submitted. How can I add a message to a form that is only rendered before the form has been submitted.
My typical code looks like this:
function buildForm() {
/**
* ...build form...
*/
$showWarning = $this->doSomeChecks();
/**
* tried to use isSubmitted() to prevent the message after submitting, but does not work
*/
if ($showWarning && !$form_state->isSubmitted()) {
$this->messenger()->addWarning('Some info you should know before submitting this form.');
}
}
function submitForm(array &$form, FormStateInterface $form_state) {
/**
* ...do stuff...
*/
$this->messenger()->addMessage('Successfully done something');
/**
* tried to use deleteByType() to remove message from buildForm after submitting, but does not work
*/
$this->messenger()->deleteByType($this->messenger()::TYPE_WARNING);
}
I know I could use $form_state->setRedirect($customPage)
in submitForm()
, but I don't want the overhead of creating a new page just to hide a simple warning message.
Is there no simple way to show a message only once on the initial form load, but not after submit?