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?

  • Can you show more code? Did you add the message properly in your submit handler? – Fons Vandamme Mar 1 '17 at 5:30
  • yes 'public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);' – Karthiga Mar 1 '17 at 5:44
  • 1
    flushed the cache? – No Sssweat Mar 1 '17 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 '17 at 6:14
  • i think you need to clear your cache. the same problem occurred with me once... – Anirban Neogi Mar 1 '17 at 6:28
2

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.

As for more OOP code, starting from Drupal 8.6, drupal_set_message() has been replaced with a service. the same code I showed (which is Drupal 8.4 code) has been changed to the following.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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