Search code examples
phpzend-framework2

How to call controller function in view in Zend Framework 2?


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 ?


Solution

  • 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/