我需要在视图中调用控制器函数并传递参数。我试图遵循这个How to call controller function in view in Zend Framework?,但它仍然无效。
我的数据库记录如下:
---------------
| name | age |
---------------
| Josh | 22 |
| Bush | 43 |
| Rush | 23 |
---------------
这是我的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>";
}
这是我的控制器:
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;
}
我希望像这样显示:
-----------------------------
| name | age | status |
-----------------------------
| Josh | 22 | You'r Young |
| Bush | 43 | You'r Old |
| Rush | 32 | You'r Young |
-----------------------------
你能帮助我吗?
答案 0 :(得分:2)
在考虑不良做法的情况下,在视图中调用控制器操作。但是你可以通过使用视图帮助器来实现这一点。所以你需要的是:
module.config.php
,以下是您可以使用的帮助:
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',
),
),
在您的视图文件中:
$this->action('Your\Controller', 'getRecordByNameAction');
希望这可以提供帮助。
答案 1 :(得分:0)
根据您需要实施viewhelpers的评论 我在这里找到了一个非常简单的解决方案这对你也很有用。
ZF2 - How can i call a function of a custom class php from a view?
在这里
https://samsonasik.wordpress.com/2012/07/20/zend-framework-2-create-your-custom-view-helper/