MageWork

Back to home

Session messages

A page can store a success or error message in the session, typically before a
redirect, and display it on the next request. The message is removed as soon as it is
read (flash message).

Set a message

From a page class:

<?php

declare(strict_types=1);

class Acme_Page_Contact_Post extends Core_Page
{
    public function execute(): void
    {
        // ... process the form ...

        $this->setSuccessMessage('Your message has been sent.');
        $this->redirect('contact.html');
    }
}
MethodDescription
setSuccessMessageStore a success message in the session
setErrorMessageStore an error message in the session
getSuccessMessageReturn and clear the success message
getErrorMessageReturn and clear the error message

Display the message

Render the message block at the top of your page template, passing the current
messages. The getSuccessMessage() / getErrorMessage() calls read the session without
starting a new one when there is nothing to show.

packages/Acme/template/page.phtml

<main>
    <div id="main-content">
        <?= $this->getBlock('block/message', ['success' => $this->getSuccessMessage(), 'error' => $this->getErrorMessage()]) ?>
        <?= $this->include($this->getContent()) ?>
    </div>
</main>

packages/Acme/template/block/message.phtml

<?php /** @var Core_Block $this */ ?>
<?php if ($this->getSuccess()): ?>
    <p class="message success"><?= App::escapeHtml($this->getSuccess()) ?></p>
<?php endif; ?>
<?php if ($this->getError()): ?>
    <p class="message error"><?= App::escapeHtml($this->getError()) ?></p>
<?php endif; ?>