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?

0

1 Answer 1

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 %}
1
  • 1
    You can still use setNotice and setError and display flashes with getFlash('notice') and getFlash('error') respectively Jun 11, 2016 at 10:02

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.