phpsessionzend-framework2

Flash messanger in zf2


How can i use flash messenger in zend freamwork 2? Session documentation is not yet. Anyone know it? But session libraries are there.


Solution

  • i have written a post about this some time ago. You can find it right here

    Basically you use it just the same like earlier.

    <?php
    public function commentAction()
    {
        // ... display Form
        // ... validate the Form
        if ($form->isValid()) {
            // try-catch passing data to database
    
            $this->flashMessenger()->addMessage('Thank you for your comment!');
    
            return $this->redirect()->toRoute('blog-details'); //id, blabla
        }
    }
    
    public function detailsAction()
    {
        // Grab the Blog with given ID
        // Grab all Comments for this blog
        // Assign the view Variables
    
        return array(
            'blog' => $blog,
            'comments' => $comments,
            'flashMessages' => $this->flashMessenger()->getMessages()
        );
    }
    

    Then in your .phtml file you do it like this:

    // details.phtml
    <?php if(count($flashMessages)) : ?>
    <ul>
        <?php foreach ($flashMessages as $msg) : ?>
        <li><?php echo $msg; ?></li>
        <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    

    Obviously this isn't all too handy, as you have to do this for every single .phtml file. Therefore doing it within the layout you have to do it at best like the following:

    <?php
    // layout.phtml
    // First get the viewmodel and all its children (ie the actions viewmodel)
    $children = $this->viewModel()
                     ->getCurrent()
                     ->getChildren();
    
    $ourView  = $children[0];
    
    if (isset($ourView->flashMessages) && count($ourView->flashMessages)) : ?>
    <ul class="flashMessages">
        <?php foreach ($ourView->flashMessages as $fMessage) : ?>
        <li><?php echo $fMessage; ?></li>
        <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    

    If you need further description, please see my blog, but i guess the code itself is pretty clear (apart frmo the layout.phtml example). Alternatively you're always free to write your own view helper to have it look a little cleaner inside your view-templates.