How can we access route, post, get, server parameters from VIEW file in ZF2 way?
Here I found the almost same question but no where mentioned about view nor answered anywhere
Thanks
You have to create a view helper to fetch these parameters for you.
Simply copy over the Zend\Mvc\Controller\Plugin\Params
to App\View\Helper\Params
and make a few adjustments:
<?php
namespace App\View\Helper;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\RequestInterface;
use Zend\View\Helper\AbstractHelper;
class Params extends AbstractHelper
{
protected $request;
protected $event;
public function __construct(RequestInterface $request, MvcEvent $event)
{
$this->request = $request;
$this->event = $event;
}
public function fromPost($param = null, $default = null)
{
if ($param === null)
{
return $this->request->getPost($param, $default)->toArray();
}
return $this->request->getPost($param, $default);
}
public function fromRoute($param = null, $default = null)
{
if ($param === null)
{
return $this->event->getRouteMatch()->getParams();
}
return $this->event->getRouteMatch()->getParam($param, $default);
}
}
Just replace all instances of $controller
with the $request
and $event
properties. You get the idea. (Don't forget to copy over the DocBlock comments!)
Next we need a factory to create an instance of our view helper. Use something like the following in your App\Module
class:
<?php
namespace App;
use App\View\Helper;
use Zend\ServiceManager\ServiceLocatorInterface;
class Module
{
public function getViewHelperConfig()
{
return array(
'factories' => array(
'Params' => function (ServiceLocatorInterface $helpers)
{
$services = $helpers->getServiceLocator();
$app = $services->get('Application');
return new Helper\Params($app->getRequest(), $app->getMvcEvent());
}
),
);
}
}
Once you have all this you're in the home stretch. Simply call up the params
view helper from within your view:
// views/app/index/index.phtml
<?= $this->params('controller') ?>
<?= $this->params()->fromQuery('wut') ?>
Hope this answers your question! Let me know if you need any clarifications.