Changing the Position of Success/Error Messages in Magento
In Magento, you can change the position of success or error messages by modifying your layout XML files. Let’s go through the process step-by-step.
Step 1: Understanding the Current Setup
The current setup places the message block using a reference to after_body_start. Here’s how it looks:
<layout>
<default>
<reference name="after_body_start">
<block type="core/template" name="top.messages" template="core/messages/top.phtml" before="-" />
</reference>
</default>
</layout>
The top.phtml file is responsible for rendering the messages. Let’s look at a simplified version of this file:
<?php $_messageCollection = $this->getMessagesBlock()->getMessageCollection(); ?>
<?php if ($_messageCollection->count()): ?>
<div>
<?php
echo $this->getMessagesBlock()->getGroupedHtml();
$_messageCollection->clear();
?>
</div>
<?php endif; ?>
This code checks for any messages, groups them by type (error or success), and then displays them inside a <div> element.
Step 2: Changing the Message Position
To move the messages to the top of the page, we need to reference before_body_start instead of after_body_start. Here’s how you do it:
<layout>
<default>
<reference name="before_body_start">
<block type="core/template" name="top.messages" template="core/messages/top.phtml" before="-" />
</reference>
</default>
</layout>
The before_body_start reference places the block right before the main content area begins.
Step 3: Customizing the Message Design
To customize the design of your messages, you need to edit the top.phtml file mentioned earlier. This is typically located at:
app/design/frontend/your_package/your_theme/template/core/messages/top.phtml
However, if you don’t see this file in that location, it’s likely because Magento 2 has moved many view files into the module structure by default.
To find the correct location, navigate to the Magento_Theme module:
vendor/magento/module-theme/view/frontend/templates/core/messages/top.phtml
In this file, you can modify the HTML and CSS to change the look of your messages. For example, you could add some custom styles:
<?php if ($_messageCollection->count()): ?>
<div class="custom-messages">
<?php
echo $this->getMessagesBlock()->getGroupedHtml();
$_messageCollection->clear();
?>
</div>
<?php endif; ?>
Then in your CSS, you could style the .custom-messages element:
.custom-messages {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
padding: 10px;
}
Conclusion
Changing the position and design of messages in Magento requires modifying layout XML files and view templates. For the most flexible customization, it’s recommended to create a theme that inherits from Magento_blank or Magento_luma and place your modified files there.
Remember to run php bin/magento cache:clean after making these changes for them to take effect.
For more detailed information on Magento 2 layout updates and custom themes, you can refer to the official documentation here.