The code you are showing is the same code Drupal core uses, for example in BanDelete::submitForm()
.
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->ipManager->unbanIp($this->banIp);
$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());
}
As drupal_set_message()
is used from Drupal core in submitForm()
, that is expected to work. I cannot say why it doesn't work in your case, since you don't show the full method code. It could also be there is a module that is interfering.
For more OOP code, drupal_set_message()
has been replaced with a service in Drupal 8.6. The code I showed (which is for Drupal 8.4) has been changed to the following. (See [BanDelete::submitForm()
][1].)
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->ipManager->unbanIp($this->banIp);
$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());
}```
[1]: https://api.drupal.org/api/drupal/core%21modules%21ban%21src%21Form%21BanDelete.php/function/BanDelete%3A%3AsubmitForm/8.9.x