Magento – Pass Data From PHTML To Block Controller

blocks

It seems wrong to me to put methods in the PHTML file. I need to loop through products in a PHTML file, but I want to call a method inside the foreach loop:

<?php
$lastOrder = $this->getLatestOrder();
$orderItems = $lastOrder->getAllItems();
?>

<?php foreach($orderItems as $item): ?>
    html stuff...
    <?php $this->getCategoryNames($item->getId()); // this doesn't work ?>
<?php endforeach; ?>

Using the code above, the getId() is always NULL in the block controller.

What is the best way to do this? Does the logic belong in the PHTML file? Should I use the Mage::registry 'globals'? I've tried setData and getData, but they don't seem to work inside a loop (reassignment issues). Thanks!

Best Answer

Consider getAllVisibileItems() instead to avoid duplicate items with configurables.

Also this code should work for what you are looking to do, untested.

$items = $order->getAllVisibleItems();
foreach ($items as $itemId => $item)
{
    $pid = $item->getProductId();
    $product = Mage::getModel('catalog/product')->load($pid);
    $cats = $product->getCategoryCollection();

    foreach ($cats as $category_id) {
        $_cat = Mage::getModel('catalog/category')->load($category_id) ;
        echo $_cat->getName();
    } 
}

I think by you calling a Block a controller and vise versa, it would be wise to refresh what a block is, what a controller is, etc...

Consider reading and better understand the toHtml method, and how blocks and layouts all work:

Hope this helps.