Magento 2 – How to Show Success or Error Message Block at Top of Page

magento2messages

I need show success or error messages block at the top of the page before the header block. As of now it appears between the breadcrumbs and main block.

Best Answer

There are a couple of ways to do this. Here is one which requires a little layout xml and a new template at a minimum…

Layout:

<layout>
    <default>
        <reference name="after_body_start">
            <block type="core/template" name="top.messages" template="core/messages/top.phtml" before="-" />
        </reference>
    </default>
</layout>

Template: app/design/frontend/your_package/your_theme/template/core/messages/top.phtml

<?php $_messageCollection = $this->getMessagesBlock()->getMessageCollection() ?>

<?php if ($_messageCollection->count()): ?>
    <div>
        <?php
        echo $this->getMessagesBlock()->getGroupedHtml();
        $_messageCollection->clear();
        ?>
    </div>
<?php endif; ?>

Alternate way

add belwo line at app/design/frontend/your_package/your_theme/Magento_Theme/laout/default.xml

<page layout="3columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    .......

    <move element="page.messages" destination="after.body.start"  after="-"/>

    ......

</page>