Nick Howarth Nick Howarth - 2 months ago 25
PHP Question

Magento 1.9.2.1 related product not adding correctly

I am building a Magento theme and am having trouble customising the way the related products work.

By default as some of you will be aware the related products system works with checkboxes. You simply tick related items and click the main "add to cart" button to add all the products at once.

I am wanting to add an "add to cart" button and quantity input for individual related items, so I can add them individually to the cart without adding the main product.

I added the following code from the link below to the template/catalog/product/list/related.phtml.

http://sarathlal.com/add-to-cart-button-in-related-products-on-product-detail-page-magento/

This adds the "add to cart" button and quantity input perfectly but when the "add to cart" button is clicked on first related product in the list the main product on the page is added instead of the related item. When I click the second, third, fourth etc in the list it weirdly adds the correct related item.

I have re-indexed everything and flushed all caches.

Can anybody advise? I would really appreciate it.

Screenshot to help with my description

Answer

If anybody reading this thread is having similar issues I have solved the problem. The issue was within the catalog/product/view.phtml file. I was rendering the related.phtml file within the products view.phtml form HTML tags. I rendered the related.phtml block outside the form and all is working.

The answer submitted by Shakir Khan will allow a "add to cart" button for the related item. if you are like me and want the quantity as well use the below code, and place it withing the loop in your related.phtml.

<form action="<?php echo $this->getAddToCartUrl($_item) ?>" method="post" id="product_addtocart_form_<?php echo $_item->getId()?>"<?php if($_item->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
       <?php if(!$_item->isGrouped()): ?>
                <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo ($this->getMinimalQty($_item)?$this->getMinimalQty($_item):1) ?>" />
                <label for="qty"><?php echo $this->__('Qty') ?>:</label>
       <?php endif; ?>
       <button type="button" onclick="this.form.submit(this)"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
</form>