Success Message After Submitting Form
In building a custom form you must keep in mind a few issues: elements, functionality, and response for best user experience
Review the following code, you can see the submit method doing few things:
- updating logger
- set message to user
- redirect the response to specific page
This code is working on Drupal 7 to 8.6
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp, ]);
drupal_set_message($this->t('The IP address %ip was deleted.', [ '%ip' => $this->banIp, ]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
from drupal 8.6, which become more service activation is written a bit differently
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp,]);
$this->messenger()->addStatus($this->t('The IP address %ip was deleted.', [ '%ip' => $this->banIp, ]));
$form_state->setRedirectUrl($this->getCancelUrl());
}
drupal_set_message
was deprecated in instead you should use the messenger service
$this->messenger() returns an instance of the messenger service, the service that replaced drupal_set_message() in Drupal 8.
Code Snippet
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->logger('user')->notice('Deleted %ip', ['%ip' => $this->banIp,]);
$this->messenger()->addStatus($this->t('The IP address %ip was deleted.', [ '%ip' => $this->banIp, ]));
$form_state->setRedirectUrl($this->getCancelUrl());
}