I need to call a controller function in my view and passing parameter. I tried to following this How to call controller function in view in Zend Framework? but it's still not working.
I have record from my database like this :
---------------
| name | age |
---------------
| Josh | 22 |
| Bush | 43 |
| Rush | 23 |
---------------
here's my index.phtml
foreach ($result as $rstd){
echo "<td>".$this->escapeHtml($rstd['name'])."</td>";
echo "<td>".$this->escapeHtml($rstd['age'])."</td>";
//here i want to access my controller function with sending parameter by name and also display something which has i set in that function.
echo "<td>** result from that function **</td>";
}
here's my controller :
public function indexAction(){
$result = $sd->getAllRecord($this->getMysqlAdapter());
return new ViewModel(array('result'=>$result));
}
public function getRecordByName($name){
if($name=='Bush'){
$result = "You'r Old";
}else{
$result = "You'r Young";
}
return $result;
}
And i want display it like this :
-----------------------------
| name | age | status |
-----------------------------
| Josh | 22 | You'r Young |
| Bush | 43 | You'r Old |
| Rush | 32 | You'r Young |
-----------------------------
Can you help me ?
Call a controller action in view in considered bad practice . But you could achieve that by using view helpers. So what you need is:
module.config.php
, Here is a helper that you could use :
class Action extends \Zend\View\Helper\AbstractHelper implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function __invoke($controllerName, $actionName, $params = array())
{
$controllerLoader = $this->serviceLocator->getServiceLocator()->get('ControllerLoader');
$controllerLoader->setInvokableClass($controllerName, $controllerName);
$controller = $controllerLoader->get($controllerName);
return $controller->$actionName($params);
}
}
module.config.php :
'view_helpers' => array(
'invokables' => array(
'action' => 'module_name\View\Helper\Action',
),
),
In your view file :
$this->action('Your\Controller', 'getRecordByNameAction');
Hope this could help.
As per the comments you need to implement viewhelpers I have found a very easy solution here. This might be useful for you too.
ZF2 - How can i call a function of a custom class php from a view?
and here
https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.