Answers:
在您的类中,注入Message ManagerInterface类:
__construct(\Magento\Framework\Message\ManagerInterface $messageManager) {
$this->messageManager = $messageManager;
}
请注意,Magento已弃用的方法:
$this->messageManager->addSuccess()
$this->messageManager->addError()
$this->messageManager->addWarning()
$this->messageManager->addNotice()
因此,您应该使用:
$this->messageManager->addSuccessMessage()
$this->messageManager->addErrorMessage()
$this->messageManager->addWarningMessage()
$this->messageManager->addNoticeMessage()
如果您使用的是控制器,那么很可能您已经扩展了
\Magento\Framework\App\Action\Action
这使用对象将\Magento\Framework\Message\ManagerInterface
对象注入其__construct
功能\Magento\Framework\App\Action\Context $context
所以要显示一条消息,
成功-
$ this-> messageManager-> addSuccess(__('这是您的成功消息。'));
错误-
$ this-> messageManager-> addError(__('这是您的错误信息。'));
警告 -
$ this-> messageManager-> addWarning(__('这是您的警告消息。'));
注意
$ this-> messageManager-> addNotice(__('这是您的通知消息。'));
在其他班级内
class Dummy
{
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
private $messageManager;
public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager)
{
$this->messageManager = $messageManager;
}
public function someFunction()
{
$this->messageManager->addSuccess('Add your success message');
}
}
据我所知,Magento2删除了特定于会话类的通知消息。