Magento – Is it possible to handle success / error messages from within blocks

layoutmagento-1

In general, I handle exceptions and display success or error messages within controllers. For example:

 Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__("The cache storage has been flushed."));

But in some cases I'd love to be able to render an error message from within a block. For example, I have blocks within my page that are dependent upon some configuration which isn't set properly currently, so what I want to do is not render those blocks but still allow other blocks around them to render.

In some cases, the other elements on the page are necessary in order to fix the problem that's causing the exception in the first place.

But I think the messages block is initialized very early in the layout rendering process, so by the time you're in a block, if you try to set a message on the session, it won't display until next page load, which would be pretty confusing of course.

I searched the core and I don't see any instance of addError() within Mage/Adminhtml/Block/

I did stumble onto this little gem, but it doesn't seem to work as I'd expect:

$this->getLayout()->getMessagesBlock()->addError('oh what');

Best Answer

You can do this by overwriting the _prepareLayout() function in your block:

protected function _prepareLayout() {
    // IF statement check for config  or something else
        $this->getMessagesBlock()->addError('oh what');
    // End of IF
    return parent::_prepareLayout();
}

_prepareLayout() is called before all of the _toHtml() functions are called on every block and after the layout has been loaded.

Related Topic