In Magento e-commerce website we usually add products to cart through add to cart button, but if we are required to add many products to cart by selecting them with the checkbox. Then we can do this as,
- Add checkbox input tag in list.phtml in <li> tag.
- Create a JavaScript function to fetch the values of the checkbox and pass the values to the ajax function
- Create an ajax function that will receive the url and id of the product and through that ajax call send the data to the cartcontroller.
- In cart controller do some changes to add data from response to the cart.
Now in magento/app/design/frontend/rwd/default/template/catalog/product/list.phtml, Add checkbox in <li> tag
<?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
<input type="checkbox" class="checkbox" id="products-checkbox<?php echo $_product->getId() ?>" name="products[]"value="<?php echo $this->getAddToCartUrl($_product)."#".$_product->getId() ?>" />
<?php endif; ?>
In the above code we have applied a condition <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?> which is to add checkboxes only for simple products. we have passed value of the checkbox with the url and id of product concatenated with '#'.
Now, above <li> tag add a button to submit the selected product with call to the js function on its onclick as.
<button type="button" class="button btn-cart" onclick="addProducts()"><span><span><span><?php echo $this->__('Add Selected to Cart') ?></span></span></span></button>
here in onclick we have called the function addProducts() which have the definition as,
function addProducts(){
var checkboxes = jQuery('input[type=checkbox]');
for (var i = 0; i <jQuery('input[type=checkbox]').length; i++) {
if(checkboxes[i].checked){
values = checkboxes[i].value;
var str = values.split("#");
url = str[0];
id = str[1];
setlocationAjax(url,id);
}
}
}
In this function we are extracting the url and id of the products one by one and passing them to the function setlocationAjax(url,id);
the definition of the ajax function works as,
function setlocationAjax(url, id){
url += 'isAjax/1';
jQuery('#ajax_loader'+id).show();
try {
jQuery.ajax({
url: url,
dataType: 'json',
type : 'post',
// data: data,
success: function(data){
// alert('sdfdsfsd');
jQuery('#ajax_loader'+id).hide();
var json = eval(data);
// jQuery('#ajax_loader').hide();
setlocationAjax(data,false);
if (jQuery('.header-minicart')) {
jQuery('.header-minicart').html( json.minicart );
}
alert(data.status + ": " + data.message);
}
});
} catch (e) {
}
}
This ajax function call sends the data to the cartcontrollers method addAction(). Now to add the data to cart we can make changes in the addAction() method as by adding this code,
if($params['isAjax'] == 1){
$response = array();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Unable to find Product ID');
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* @todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$cart->getQuote()->getHasError()){
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$response['status'] = 'SUCCESS';
$response['message'] = $message;
//New Code Here
$this->loadLayout();
$toplink = $this->getLayout()->getBlock('top.links')->toHtml();
$sidebar_block = $this->getLayout()->getBlock('cart_sidebar');
Mage::register('referrer_url', $this->_getRefererUrl());
//$sidebar = $sidebar_block->toHtml();
$response['toplink'] = $toplink;
$response['sidebar'] = $sidebar;
$minicart = $this->getLayout()->getBlock('minicart_head')->toHtml();
$response['minicart'] = $minicart;
// $cart = $this->getLayout()->getBlock('toplink')->toHtml();
// $response['cart'] = $cart;
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message.'<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add the item to shopping cart.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}else{
return parent::addAction();
}
}
0 Comment(s)