I have a plugin that accepts a form post. I need to return a notice or error, plus the original data. Starting with the notice/error first, I have tried this:

if (craft()->broadbean_jobs->createJob())
{
    craft()->userSession->setNotice(Craft::t('Job created.'));
}
else
{
    craft()->userSession->setError(Craft::t('Unable to create job.'));
}

$this->redirectToPostedUrl();

How can I display the notice or error in my template?

  • Is this for frontend or backend? In backend it's default but on frontend I would use flash messages instead. – naboovalley Nov 5 '14 at 21:18
  • This is for the frontend. I've ended up passing the message back with posted form data. How would the flash message approach work? – Russ Back Nov 6 '14 at 8:27
  • Added an answer for ya :) – naboovalley Nov 6 '14 at 9:28
up vote 13 down vote accepted

You can use the setFlash function in the userSession Service like this:

In your Controller:

craft()->userSession->setFlash('yourVariable', "Something happened yo!");

In your template (that the user gets redirected to):

{% set message = craft.session.getFlash('yourVariable') %}

After that just run an if-statement to see if the message is set or not.

EDIT: In Craft 3 controller:

Craft::$app->session->setFlash('yourVariable', "Something happened yo!");

In template:

{% set message = craft.app.session.getFlash('yourVariable') %}
{% if message|length > 0 %}
    {{message}}
{% endif %}
  • You can still use setNotice and setError and display flashes with getFlash('notice') and getFlash('error') respectively – Yuri Salimovskiy Jun 11 '16 at 10:02

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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