Magento2 – Set Array Data in Controller and Call in PHTML

blockscontrollersmagento2module

Controller

public function execute()
    {

        $bags_result = array(   'height'=>$height,
                                'weight'=>$weight
                            );

        $result = $this->resultJsonFactory->create();
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()
                ->createBlock('Vendor\Module\Block\Index')
                ->setTemplate('Vendor_Module::calculation.phtml')
                ->setData('bags_result',$bags_result)
                ->toHtml();

        $result->setData(['output' => $block]);
        return $result;
    } 

Block File function

public function getBagsResultData()
    {
        return $this->getBagsResult();
    }

calculations.phtml

<label><?php echo __('Height')?><span id="final-bmi-data"><?php echo $this->getBagsResultData('height')?></span></label>
<label><?php echo __('Weight')?><span id="final-bmi-data"><?php echo $this->getBagsResultData('weight')?></span></label>

Even if I change and use $block->getBagsResultData(); it gives the below error.

Error: 1 exception(s): Exception #0 (Exception): Notice: Array to
string conversion

How do I fetch and display array data set in controller using block or directly in phtml ?

Best Answer

Try this

public function getBagsResultData($var)
    {
        return $this->getBagsResult($var);
    }

or

 public function getBagsResultData($var)
    {
        $data = $this->getBagsResult();
        return $data[$var];
    }

In phtml you are passing the index but in method you output the array.

 <label><?php echo __('Height')?><span id="final-bmi-data"><?php echo $this->getBagsResultData('height')?></span></label>
<label><?php echo __('Weight')?><span id="final-bmi-data"><?php echo $this->getBagsResultData('weight')?></span></label>