6

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?

Russ Back
  • 1,503
  • 13
  • 26

1 Answers1

16

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 %}
lenka
  • 180
  • 9
naboovalley
  • 2,844
  • 1
  • 16
  • 26