سؤال

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');
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I'm not sure, wether I understand you correct.

You can get the Message Block via

Mage_Core_Block_Abstract::getMessagesBlock()
// means $this in block context (template and Block class)

there you can everything you want, for example add new errors:

$this->getMessagesBlock()->addError('Configuration is wrong!');

or show the error messages with your own template:

$this->getMessageBlock()->setTemplate('my_template.phtml');
echo $this->getMessageBlock()->toHtml();

Have a look on the following methods to change the layout of the messages:

Mage_Core_Block_Messages::setMessagesFirstLevelTagName()
Mage_Core_Block_Messages::setMessagesSecondLevelTagName()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top