从视图中调用控制器 - Zend Framework

时间:2014-02-27 16:28:23

标签: php zend-framework zend-framework2

如何在视图中呈现控制器的结果......?

这就是我目前正在做的事情,但由于视图是直接调用的......它不会从我的控制器中获取模型。这是愚蠢的。

public function ListAction()
{
    $sm = $this->getServiceLocator();
    $this->userRepository = $sm->get('Application\Model\Concrete\TGUserRepository');

    $users = $this->userRepository->Users();

    $view = new ViewModel( array( "Users" => $users ) );

        $secondarySidebarView = new ViewModel(); // I don't really wanna do this, because I've already got an awesome controller set up for this which may as well be used to generate the model :S ?
        $secondarySidebarView->setTemplate('something/poo'); // This only gets the view and doesn't call the controller first :S

    $view->addChild($secondarySidebarView, 'something');
    return $view;
}

视图:

<?php    
    foreach( $this->Users as $user )
    {
        echo $user->Email;
    }

    echo $this->something; // Works fine
    print_r( $this->something->Poos ); // Crashes because the controller hasn't been called to generate the Poos :(

我想在我的观点中做的事情是这样的:

echo RenderFromController( "action", "controllername" );

1 个答案:

答案 0 :(得分:0)

以下是实现这一目标的方法:

public function listAction()
{

     $view = new ViewModel();
     $view->setTemplate('users.phtml');
     $poos = $this->forward()
                   ->dispatch('Foo\Controller', array('action' => 'action-name'));
     $view->addChild($poos, 'Poos');

     /* Add more variables to $view as needed */

     return $view;
}
users.phtml中的

<?php

    echo $this->poos; //Will output the result of Foo\Controller::action-name