Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

}
like image 685
Thanu Avatar asked Jan 20 '14 06:01

Thanu


2 Answers

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();
like image 93
Mr_Green Avatar answered Sep 22 '22 00:09

Mr_Green


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');
like image 31
Asif hhh Avatar answered Sep 18 '22 00:09

Asif hhh