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?

15
  • 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 class 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 Drupal 8.4 code) has been changed to the following. (See BanDelete::submitForm().)

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());
}

$this->messenger() returns an instance of the messenger service, the service that replaced drupal_set_message() in Drupal 8.

Your Answer

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

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