2

I am try to display an success message after submitting my form and redirect to next page. The code I am using is the following.

public function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

It doesn't work for me.

Is there any alternate way to do it? What code should I use to display a success message?

16
  • Can you show more code? Did you add the message properly in your submit handler? Mar 1, 2017 at 5:30
  • yes 'public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);'
    – Karthiga
    Mar 1, 2017 at 5:44
  • 1
    flushed the cache?
    – No Sssweat
    Mar 1, 2017 at 6:11
  • The above code should work.Make sure your form is loading. Clear the cache. Steps given in below link I feel useful.just cross check the steps you followed with this link.Hope it is helpful. valuebound.com/resources/blog/…
    – rks
    Mar 1, 2017 at 6:14
  • i think you need to clear your cache. the same problem occurred with me once... Mar 1, 2017 at 6:28

1 Answer 1

5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.