简体   繁体   中英

Zend Framework: How to call an Action from a View?

I'm having a problem with Action View Helper when I am trying to call an action from a view script. The view is located in /views/scripts/home and it belongs to HomeController and i want to access an action from BookController.

I have the following code in my view:

foreach ($this->books as $book) {

    if (!empty($book['asin'])) {     
        $bookObj = $this->action('get-book-by-asin', 'book', null, 
                                 array('asin' => $book['asin']));

In getBookByAsinAction() I want to return a $data variable. How to send it back as a response to the Action View Helper call?

I now that I can do a foreach through $books variable in my controller instead of doing it in my view but i'm just curious. Or maybe in the future i will use Action View Helper when a particular action could generate more useful re-usable content or "widget-ized" content.

If I get many rows from a DB query then would it be better to do just a foreach instead of two? One foreach would be in the View, to render the result properly, and I should consider doing another one in the Controller to check if a book has or has not an ASIN and then call for eg a web service. Is this an optimal solution?

Or is it better to use Action View Helper in the way described?

you could just create a new action helper , then call it with the action helper broker in your view :

Let say you create an action helper called getBookByAsin :

in the code view :

$gbba= Zend_Controller_Action_HelperBroker::getStaticHelper('getBookByAsin');

$var = $gbba->direct("asin");

My solution was to end getBookByAsinAction() with the following line: $this->_response->setBody(json_encode($data)); and in my View $book = (array) json_decode($bookObj);

I didn't create a get-book-by-asin.phtml view for this action so I've added $this->_helper->viewRenderer->setNoRender();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM