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

Laurence Cope
  • 512
  • 3
  • 12
  • AFAIK it is not possible to set a flash message from the template, however this might be a nice improvement for the {% redirect %} tag. – Oliver Stark Jan 14 '19 at 09:09
  • 1
    Now (Craft 3.1) you can set a notice/error message with the {% redirect %} tag: https://docs.craftcms.com/v3/dev/tags/redirect.html#flash-messages – Oliver Stark Jan 15 '19 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. – Laurence Cope Jan 16 '19 at 10:51
  • Laurence, it was added to the docs yesterday, along with the Craft 3.1 release ;-) https://github.com/craftcms/cms/pull/3625 – Oliver Stark Jan 17 '19 at 08:59

2 Answers2

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.

Brandon Kelly
  • 34,307
  • 2
  • 71
  • 137
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 %}
Oli
  • 7,495
  • 9
  • 17