Thanu
Thanu

Reputation: 2501

Magento How to pass data from a controller to a template?

I have a controller action that connects to a XML feed and bring some data from a third party application. Now I want this data to be presented in my Magento product page. Controller action get called as an ajax call by a parent template file and data has to be rendered in to one of the child templates.

I know if I had a Model then that can talk to a Block and then the data can be available at template level. But not sure how this can be done through a controller action. So far I managed to dump the data to the child template but not the fully rendered HTML. (I dont want to build the HTML in the controller and dump it to the template as it is bad practice I reckon)

Following is my controller action and getProduct

public function getFeedbackAction()
{

    $url = 'http://3rd-party-domain/some-module/xmlfeed.php';

    $xml_feed = simplexml_load_file($url);

    foreach ($xml_feed as $key=>$feedback){
        if ($key == "PRODUCT") {
            $this->feedbacks[] = $feedback;
        }
    }

    if ($this->getRequest()->getParam('type') == 'product'){
        $sku = $this->getRequest()->getParam('sku');
        if ( $sku != ""){
            $this->getProductReviews($sku); 
        }
    } 
}

private function getProductReviews($sku){

    foreach ($this->feedbacks as $feedback){
        if ($feedback->PRODUCTCODE == $sku){
            $productreviews[] = $feedback;
        }
    }

    Zend_Debug::dump($productreviews);

    //echo $this->getLayout()->createBlock('mymodule/reviews')->setTemplate('mymodule/reviews.phtml')->toHtml();

}

Upvotes: 6

Views: 16150

Answers (2)

Mr_Green
Mr_Green

Reputation: 41832

In addition to asif's answer, we can also do :

In controller:

$layout = $this->getLayout();
$block = $layout->getBlock('block_name');
$block->setFeedback($feedback); //magic method

and then in phtml file:

$feedback = $this->getFeedback();

Upvotes: 14

Asif hhh
Asif hhh

Reputation: 1552

you can use

Mage::register('feedback', $feedback);

this data will be available to the template, that comes in scope of that action, and you can get that data in template as ...

Mage::registry('feedback');

Upvotes: 4

Related Questions