2

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

  • 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 at 9:09
  • 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 – Oliver Stark Jan 15 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 at 10:51
  • Laurence, it was added to the docs yesterday, along with the Craft 3.1 release ;-) github.com/craftcms/cms/pull/3625 – Oliver Stark Jan 17 at 8:59
7

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.

4

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 %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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