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:

$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!

1 Answer 1


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.

  • Thank you Boomer, very helpful. I guess the logic does belong in the phtml file then.
    – Jongosi
    Commented Jul 17, 2013 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.