4

How does one set a flash message in the templates? I can't find any documentation about this, only for plugins or getting the message.

My use-case is, I am checking if a user is allowed to access a certain page and if they cannot I want to set a flash message, then redirect them to another page. I prefer this than to keep them on the same page and is if else logic to show the message or the rest of the page.

Thanks

4
  • AFAIK it is not possible to set a flash message from the template, however this might be a nice improvement for the {% redirect %} tag. Commented Jan 14, 2019 at 9:09
  • 1
    Now (Craft 3.1) you can set a notice/error message with the {% redirect %} tag: docs.craftcms.com/v3/dev/tags/redirect.html#flash-messages Commented Jan 15, 2019 at 23:52
  • redirect with flash notice is great. I had not found that documentation because its within the redirect documentation, whereas I had been searching for flash and did not find this page! Thanks. Commented Jan 16, 2019 at 10:51
  • Laurence, it was added to the docs yesterday, along with the Craft 3.1 release ;-) github.com/craftcms/cms/pull/3625 Commented Jan 17, 2019 at 8:59

2 Answers 2

13

You can set flash messages using yii\web\Session::setFlash().

The session component is available to templates via craft.app.session.

{% do craft.app.session.setFlash('error', 'You’re not allowed to go there.') %}

For convenience, Craft’s SessionBehavior class adds shortcut setError() and setNotice() methods to the session component as well.

{% do craft.app.session.setError('You’re not allowed to go there.') %}

You can place that right before your {% redirect %} tag.

0
10

Edit: Brandon replied as I was writing this. Feel free to remove :)

You can do that using this in your conditional, just above your redirect tag

{% do craft.app.session.setFlash('error', 'no no no') %}
{% redirect "tosomewhere" %}

Then in the template you are redirecting to

{% set message = craft.app.session.getFlash('error', null, true) %}
{% if message %}
    {{ message }}
{% endif %}
0

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.