Magento 1.8 Product Listing – How to Modify ‘Add to Cart’ Button

magento-1.8magento-enterpriseproduct-list

I'm building a self contained module which will make modifications to the 'Add to Cart' button through Magento's listing and detail pages. I can easily modify the button on the detail page as it uses it's own template addtocart.phtml.

Where as the listing page has the mark up for these buttons embedded in a chunk of HTML. The code for the button is below.

<?php if($_product->isSaleable()): ?>
    <p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
<?php else: ?>
    <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
<?php endif; ?>

My issue is trying to modify the above code without having to ask the installer to make numerous code changes. Obviously if the site is running a heavily modified template they will need to.

I could provide a new list.phtml template and override the entirety of the file but this seems like it's going to cause more issues then it's worth.

Short of writing some dirty hack to attempt to locate this button and make the modifications is there a better solution? What would you suggest to be the best solution in a contained module as well?

Best Answer

Your definition of dirty is a bit much, since each block registers an event that allows you to modify it's HTML after it's processed it itself. And then there's JavaScript as well.

In fact, I'd say the clean way is to use this core_block_abstract_to_html_after event, because rewriting the template to include another template for this button, causes much more overhead. Instead in core_block_abstract_to_html_after you can do a single preg_replace pass, or a maybe somewhat cleaner DOM replacement.