I was wondering if it is possible or how to be able to define a ViewModel in the Application module and pass it to display in the layout.phtml in Zend Framework 2. Here is the code for the Application Controller:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$container = new Container('session');
return new ViewModel(array('username' => $container->username,
'password' => $container->password));
}
}
This is the layout.phtml page I am trying to get username to display
<ul class="nav navbar-nav navbar-right">
<li><p class="navbar-text" style="font-family: Papyrus, fantasy; font-size: 20px;">
<?php echo $username; ?></p></li>
</ul>
Any help would be appreciated.
If you want to display anything in layout ViewModel which is called root ViewModel you should use your controller`s layout() plugin:
class IndexController extends AbstractActionController
{
public function indexAction()
{
$container = new Container('session');
$mainLayout = $this->layout();
$mainLayout->setVariable('foo', 'bar'); //it accepts array too
return new ViewModel(array('username' => $container->username,
'password' => $container->password));
}
}
In layout.phtml
<?php echo $this->foo ;?> // or just $foo
As a side note use plugins and view helpers for displaying user name or other user related stuff especial if your user is logged in. Check Zend\Authentication and plugin identity() its in Zend\Mvc\Controller\Plugin\Identity.php and check out its factory in Zend\Mvc\Controller\Plugin\Service\IdentityFactory.php
You can always make your own identity plugin and use your custom factory to customize it.