herveguetin
4/2/2014 - 10:34 PM

Use renderers for shipping methods in Magento

Use renderers for shipping methods in Magento

<?php
class Your_Module_Helper_Shipping extends Mage_Core_Helper_Abstract

    public function getShippingRatesHtml($code, $rates, $sole = true)
    {
        $defaultBlockClass = 'Your_Module_Block_Shipping_Method_Renderer_Default';
        $codeBlockClass = 'Your_Module_Block_Shipping_Method_Renderer_' . ucfirst($code);

        $block = Mage::app()->getLayout()->createBlock($codeBlockClass);
        if(!$block) {
            $block = Mage::app()->getLayout()->createBlock($defaultBlockClass);
        }

        $block->setCode($code)
            ->setRates($rates)
            ->setSoleFlag($sole)
        ;

        return $block->toHtml();
    }
}
<?php
class Your_Module_Block_Shipping_Method_Renderer_Default extends Mage_Checkout_Block_Onepage_Shipping_Method_Available
{

    const DEFAULT_TEMPLATE = 'checkout/onepage/shipping_method/default.phtml';

    protected $_soleFlag = true;
    protected $_code = '';


    /**
     * Set carrier code
     *
     * @param string $code
     * @return Your_Module_Block_Shipping_Method_Renderer_Default
     */
    public function setCode($code)
    {
        $this->_code = $code;
        return $this;
    }

    /**
     * Get carrier code
     *
     * @return string
     */
    public function getCode()
    {
        return $this->_code;
    }

    /**
     * Set rates
     *
     * @param array $rates
     * @return Your_Module_Block_Shipping_Method_Renderer_Default
     */
    public function setRates($rates)
    {
        $this->_rates = $rates;
        return $this;
    }

    /**
     * Set sole flag
     *
     * @param bool $flag
     * @return Your_Module_Block_Shipping_Method_Renderer_Default
     */
    public function setSoleFlag($flag)
    {
        $this->_soleFlag = $flag;
        return $this;
    }

    /**
     * Set sole flag
     *
     * @return bool
     */
    public function isSole()
    {
        return $this->_soleFlag;
    }

    protected function _beforeToHtml()
    {
        $codeTemplate = 'checkout/onepage/shipping_method/' . strtolower($this->getCode()) . '.phtml';
        $this->setTemplate($codeTemplate);

        $templateFile = Mage::getBaseDir('design') . DS . $this->getTemplateFile();
        if (!file_exists($templateFile)) {
            $this->setTemplate(self::DEFAULT_TEMPLATE);
        }

        return parent::_beforeToHtml();
    }
}
<dl class="sp-methods">
    <?php $shippingCodePrice = array(); ?>
    <?php $_sole = count($_shippingRateGroups) == 1; foreach ($_shippingRateGroups as $code => $_rates): ?>
        <?php echo Mage::helper('your_module/shipping')->getShippingRatesHtml($code, $_rates, $_sole); ?>
    <?php endforeach; ?>
</dl>