SilverStripe Multiple Session Messages UPDATED!

Posted by on 21 January 2015

In a few jobs recently I have found the need for multiple session messages. I found the standard form message only lets you add one message or one per field. Please use / modify the following code to get multiple session messages.

Add the following code to /mysite/Page.php

    public function addMessage($message, $type = 'success', $canclose = true) {
		 Session::add_to_array('Messages', array(
            'Message' => $message,
            'MessageType' => $type,
            'CanClose' => $canclose
		));
	}

    public function getMessages() {
		 if($messages = Session::get('Messages')){
            Session::clear('Messages');
			$ArrayList = new ArrayList();
			foreach($messages as $message) {
				$ArrayList->push(new ArrayData(array(
					'Message' => $message['Message'],
					'MessageType' => $message['MessageType'],
					'CanClose' => $message['CanClose']
				)));
			}
			return $ArrayList;
        }
    }
// this clears any previous messages and sets only this message
    public function setMessage($message, $type = 'success', $canclose = true) {
	    Session::clear('Messages');
		$this->addMessage($message, $type, $canclose);
    }

Then include the following in your template. Note, this code is set up to use uikit.

<% if $Messages %>
<% loop $Messages %>
<div class="uk-alert uk-alert-{$MessageType}"<% if $CanClose %> data-uk-alert<% end_if %>>
<% if $CanClose %><a href="" class="uk-alert-close uk-close"></a><% end_if %>
<p>$Message</p>
</div>
<% end_loop %>
<% end_if %>

Updated 9 Dec 2015

I noticed there is an issue with this code in later versions of SilverStripe. Try also adding the below function to the Page_Controller. The problem occurs due to checking for $Messages with the first {if} statement. This was causing the Session to clear.

    public function IsMessages() {
		$messages = Session::get('Messages');
		return (!empty($messages));
	}

And also adjust the template to use <% if $IsMessages %>.

<% if $IsMessages %>
<% loop $Messages %>
<div class="uk-alert uk-alert-{$MessageType}"<% if $CanClose %> data-uk-alert<% end_if %>>
<% if $CanClose %><a href="" class="uk-alert-close uk-close"></a><% end_if %>
<p>$Message</p>
</div>
<% end_loop %>
<% end_if %>

Like to make an inquiry? Contact Us