4

I'm styling my flash messages in Craft Commerce - I added if statements to detect the type of flash message. I noticed however that the message no longer displays but the styling does get picked up. Any ideas what I might need to do here?

{% if craft.session.getFlash('notice') %}
    <div data-alert class="alert-box info radius">
      {{ craft.session.getFlash('notice') }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}

{% if craft.session.getFlash('error') %}
    <div data-alert class="alert-box alert radius">
      {{ craft.session.getFlash('error') }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}
9

Getting a flash message also deletes it, so you should set it to a variable first, otherwise, when you try to access it a second time, it will be empty.

So you need to do something like this:

{% set flashNotice = craft.session.getFlash('notice') %}
{% if flashNotice %}
    <div data-alert class="alert-box info radius">
      {{ flashNotice }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}

{% set flashError = craft.session.getFlash('error') %}
{% if flashError %}
    <div data-alert class="alert-box alert radius">
      {{ flashError }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}
6

You can use hasFlash() instead, or pass false as a third argument, otherwise the flash message is discarded after the first time it is accessed.

{% if craft.session.getFlash('notice', null, false) %}
    <div data-alert class="alert-box info radius">
      {{ craft.session.getFlash('notice') }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}

or

{% if craft.session.hasFlash('error') %}
    <div data-alert class="alert-box alert radius">
      {{ craft.session.getFlash('error') }}
      <a href="#" class="close">&times;</a>
    </div>
{% endif %}

This is because flash messages are generally designed to be accessed or displayed only once, on the subsequent request.

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.