FlashMessenger in Zend 2

狂风中的少年 提交于 2019-12-08 05:42:29

问题


I am doing zend 2 Study. Now I checkout flashMessenger helper. It seems there are no documented way to call flashMessenger at layout.php. because I want to show all messages (error or success) at div located at layout, I need to call flashMessenger there. I do not want to send messages everytime via controller's actions and just want action only add message and layout show them.

While I am open to custom helper/libs But builtin solution is the best. ( I do not much work on zend 1 also, So I did not know if it is easily possible with even zend 1. )

I checkout one post How do I access flashmessenger in my layout file, in zend framework? But it have custom solution for zend 1. So I am thinking if zend have no built in solution at all in both 1 & 2.


回答1:


i just wrote my own simple viewhelper:

<?php

namespace My\View\Helper;

use Zend\View\Helper\AbstractHelper;

class FlashMessenger extends AbstractHelper
{
    protected static $_flashMessenger;

    public function __invoke($namespace = 'default') {

        if (!self::$_flashMessenger) {

            self::$_flashMessenger = new \Zend\Mvc\Controller\Plugin\FlashMessenger;
        }

        return self::$_flashMessenger->setNamespace($namespace);
    }
}

use it like:

<? if ($this->flashMessenger()->hasMessages()): ?>
    <ul>
    <? foreach ($this->flashMessenger()->getMessages() as $message): ?>
        <li><?= $message></li>
    <? endforeach ?>
    </ul>
<? endif ?>



回答2:


In your Controller method add this

$this->flashMessenger()->addMessage('Your Flash message');

In module/Application/view/layout/{your-layout.phtml} add this:

<div>
 <?php if ($this->flashMessenger()->hasMessages()): ?>
    <div class="alert alert-info">
        <?php foreach ($this->flashMessenger()->getMessages() as $message): ?>
            <?php echo $message; ?>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

I think this will help solve your problem.



来源:https://stackoverflow.com/questions/12136855/flashmessenger-in-zend-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!