How To Add Product From A Wishlist Successfully

Have you ever encountered a problem with adding an item to shopping cart from an email yet? If the answer is Yes, then you could take some time to read this article for some efficient solutions to tackle the issue. Kick it off!

A quick reminder: We’ve just released the version 2.0 of Claue Multipurpose Magento 2 Theme, with with a bunch of performance improvements and exclusive features. Check this theme out now: Claue Magento Theme  2. 0 

Claue – Clean, Minimal Magento 2&1 Theme is an excellent template for a modern and clean eCommerce store with 40+ homepage layouts and tons of options for shop, blog, portfolio, store locator layouts and other useful pages. Claue version 2. 0  has been released with a bunch of performance improvements and exclusive features including:

  • Being based on Luma theme.
  • Meet all standards of Magento Theme
  • Significant performance improvement
  • Compatible with most third-party extensions.
  • Fully compatible with Magento 2.4.x
claue-2.0

So, let’s get to the main topic, shall we?

How to eliminate this kind of trouble instantly?

The problem is mostly seen in Magento 1.9.0.1 when a customer shares his wishlist to some of his friends via email. The customer himself will receive a copy of that email which lists product links, Add to cart and Add all items to shopping cart… Error found if the customer click Add to cart or All all items to shopping cart.

Particularly, when you click Add to cart for each of every product in the list, a new tab in the browser is open linking to shopping cart page but you cannot add that product to your cart. Similarly, when you click Add all items to cart, a new page of 404 error is found.

What we do is to create a Wishlist module in namespat MGS to rewrite block and add controller. The structure of the module is written as follows:

[php]

app/code/local/MGS/Wishlist/Block/Share/Email/Items.php
app/code/local/MGS/Wishlist/ controllers/CartController.php
app/code/local/MGS/Wishlist/ controllers/ SharedController.php
app/code/local/MGS/Wishlist/ etc/config.xml
app/etc/modules/ MGS_Wishlist.xml

[/php]

Then declare MGS_wishlist module in app/etc/modules/ MGS_Wishlist.xml like this:

[php]

<?xml version="1.0"?>
<config>
<modules>
<MGS_Wishlist>
<active>true</active>
<codePool>local</codePool>
</MGS_Wishlist>
</modules>
</config>

[/php]

In app/code/local/MGS/Wishlist/ etc/config.xml, you willrewrite block and add controller as follows:

[php]

<frontend>
<routers>
<wishlist>
<args>
<modules>
<mgs_wishlist before="Mage_Wishlist">MGS_Wishlist</mgs_wishlist>
</modules>
</args>
</wishlist>
<checkout>
<args>
<modules>
<mgs_wishlist before="Mage_Checkout">MGS_Wishlist</mgs_wishlist>
</modules>
</args>
</checkout>
</routers>
</frontend>
<global>
<blocks>
<wishlist>
<rewrite>
<share_email_items>MGS_Wishlist_Block_Share_Email_Items</share_email_items>
</rewrite>
</wishlist>
</blocks>
</global>

[/php]

In app/code/local/MGS/Wishlist/Block/Share/Email/Items.php block, add a sharing parameter to the Add to cart URL like this:

$additional[‘share’] = 1;

In app/code/local/MGS/Wishlist/ controllers/ SharedController.php file, add an “allcart” action to Add all items to shopping cart

[php]
public function allcartAction() {
$wishlist = $this->_getWishlist();
if (!$wishlist) {
$this->_forward(‘noRoute’);
return;
}
$isOwner = $wishlist->isOwner(Mage::getSingleton(‘customer/session’)->getCustomerId());

$messages = array();
$addedItems = array();
$notSalable = array();
$hasOptions = array();

$cart = Mage::getSingleton(‘checkout/cart’);
$collection = $wishlist->getItemCollection()
->setVisibilityFilter();

$qtysString = $this->getRequest()->getParam(‘qty’);
$qtys = array();
if (isset($qtysString))
$qtys = array_filter(json_decode($qtysString), ‘strlen’);

foreach ($collection as $item) {
/** @var Mage_Wishlist_Model_Item */
try {
$disableAddToCart = $item->getProduct()->getDisableAddToCart();
$item->unsProduct();

// Set qty
if (count($qtys)) {
if (isset($qtys[$item->getId()])) {
$qty = $this->_processLocalizedQty($qtys[$item->getId()]);
if ($qty) {
$item->setQty($qty);
}
}
} else {
$item->setQty(1);
}
$item->getProduct()->setDisableAddToCart($disableAddToCart);
// Add to cart
if ($item->addToCart($cart, $isOwner)) {
$addedItems[] = $item->getProduct();
}
} catch (Mage_Core_Exception $e) {
if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_NOT_SALABLE) {
$notSalable[] = $item;
} else if ($e->getCode() == Mage_Wishlist_Model_Item::EXCEPTION_CODE_HAS_REQUIRED_OPTIONS) {
$hasOptions[] = $item;
} else {
$messages[] = $this->__(‘%s for "%s".’, trim($e->getMessage(), ‘.’), $item->getProduct()->getName());
}

$cartItem = $cart->getQuote()->getItemByProduct($item->getProduct());
if ($cartItem) {
$cart->getQuote()->deleteItem($cartItem);
}
} catch (Exception $e) {
Mage::logException($e);
$messages[] = Mage::helper(‘wishlist’)->__(‘Cannot add the item to shopping cart.’);
}
}

if ($isOwner) {
$indexUrl = Mage::helper(‘wishlist’)->getListUrl($wishlist->getId());
} else {
$indexUrl = Mage::getUrl(‘wishlist/shared’, array(‘code’ => $wishlist->getSharingCode()));
}
if (Mage::helper(‘checkout/cart’)->getShouldRedirectToCart()) {
$redirectUrl = Mage::helper(‘checkout/cart’)->getCartUrl();
} else if ($this->_getRefererUrl()) {
$redirectUrl = $this->_getRefererUrl();
} else {
$redirectUrl = $indexUrl;
}

if ($notSalable) {
$products = array();
foreach ($notSalable as $item) {
$products[] = ‘"’ . $item->getProduct()->getName() . ‘"’;
}
$messages[] = Mage::helper(‘wishlist’)->__(‘Unable to add the following product(s) to shopping cart: %s.’, join(‘, ‘, $products));
}

if ($hasOptions) {
$products = array();
foreach ($hasOptions as $item) {
$products[] = ‘"’ . $item->getProduct()->getName() . ‘"’;
}
$messages[] = Mage::helper(‘wishlist’)->__(‘Product(s) %s have required options. Each of them can be added to cart separately only.’, join(‘, ‘, $products));
}

if ($messages) {
$isMessageSole = (count($messages) == 1);
if ($isMessageSole && count($hasOptions) == 1) {
$item = $hasOptions[0];
if ($isOwner) {
$item->delete();
}
$redirectUrl = $item->getProductUrl();
} else {
// $wishlistSession = Mage::getSingleton(‘wishlist/session’);
foreach ($messages as $message) {
Mage::getSingleton(‘checkout/session’)->addError($message);
}
$redirectUrl = $indexUrl;
}
}

if ($addedItems) {
// save wishlist model for setting date of last update
try {
$wishlist->save();
} catch (Exception $e) {
Mage::getSingleton(‘wishlist/session’)->addError($this->__(‘Cannot update wishlist’));
$redirectUrl = $indexUrl;
}

$products = array();
foreach ($addedItems as $product) {
$products[] = ‘"’ . $product->getName() . ‘"’;
}

Mage::getSingleton(‘checkout/session’)->addSuccess(
Mage::helper(‘wishlist’)->__(‘%d product(s) have been added to shopping cart: %s.’, count($addedItems), join(‘, ‘, $products))
);

// save cart and collect totals
$cart->save()->getQuote()->collectTotals();
}

Mage::helper(‘wishlist’)->calculate();

$redirectUrl = Mage::helper(‘checkout/cart’)->getCartUrl();

$this->_redirectUrl($redirectUrl);
}

[/php]

We need to examine the existence of “share” parameter we added to the URL as mentioned above in app/code/local/MGS/Wishlist/ controllers/CartController.php

We also add another condition to examine the existence of “share” parameter in     function _goBack(). If it works, function_goBack() will redirect to URL: Mage::getUrl(‘checkout/cart’).

[php]
protected function _goBack() {
$returnUrl = $this->getRequest()->getParam(‘return_url’);
if ($returnUrl) {

if (!$this->_isUrlInternal($returnUrl)) {
throw new Mage_Exception(‘External urls redirect to "’ . $returnUrl . ‘" denied!’);
}

$this->_getSession()->getMessages(true);
$this->getResponse()->setRedirect($returnUrl);
} elseif (!Mage::getStoreConfig(‘checkout/cart/redirect_to_cart’)
&& !$this->getRequest()->getParam(‘in_cart’)
&& $backUrl = $this->_getRefererUrl()
) {
$is_share = $this->getRequest()->getParam(‘share’);
if(isset($is_share))
$this->getResponse()->setRedirect(Mage::getUrl(‘checkout/cart’));
else
$this->getResponse()->setRedirect($backUrl);
} else {
if (($this->getRequest()->getActionName() == ‘add’) && !$this->getRequest()->getParam(‘in_cart’)) {
$this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
}
$this->_redirect(‘checkout/cart’);
}
return $this;
}

[/php]

Additionally, we will examine the existence of “share” parameter in addAction() function to combine with the existing condition of form key for the final result of working           function_goBack().

[php]

$params = $this->getRequest()->getParams();
if (!$this->_validateFormKey() && !isset($params[‘share’])) {
$this->_goBack();
return;
}

[/php]

Below you will find the precise code for app/code/local/MGS/Wishlist/ controllers/CartController.php

[php]

require_once ‘Mage/Checkout/controllers/CartController.php’;

class MGS_Wishlist_CartController extends Mage_Checkout_CartController {

protected function _goBack() {
$returnUrl = $this->getRequest()->getParam(‘return_url’);
if ($returnUrl) {

if (!$this->_isUrlInternal($returnUrl)) {
throw new Mage_Exception(‘External urls redirect to "’ . $returnUrl . ‘" denied!’);
}

$this->_getSession()->getMessages(true);
$this->getResponse()->setRedirect($returnUrl);
} elseif (!Mage::getStoreConfig(‘checkout/cart/redirect_to_cart’)
&& !$this->getRequest()->getParam(‘in_cart’)
&& $backUrl = $this->_getRefererUrl()
) {
$is_share = $this->getRequest()->getParam(‘share’);
if(isset($is_share))
$this->getResponse()->setRedirect(Mage::getUrl(‘checkout/cart’));
else
$this->getResponse()->setRedirect($backUrl);
} else {
if (($this->getRequest()->getActionName() == ‘add’) && !$this->getRequest()->getParam(‘in_cart’)) {
$this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
}
$this->_redirect(‘checkout/cart’);
}
return $this;
}

public function addAction()
{
$params = $this->getRequest()->getParams();
if (!$this->_validateFormKey() && !isset($params[‘share’])) {
$this->_goBack();
return;
}
$cart = $this->_getCart();
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) {
$this->_goBack();
return;
}

$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 (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()) {
$message = $this->__(‘%s was added to your shopping cart.’, Mage::helper(‘core’)->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper(‘core’)->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper(‘core’)->escapeHtml($message));
}
}

$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper(‘checkout/cart’)->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__(‘Cannot add the item to shopping cart.’));
Mage::logException($e);
$this->_goBack();
}
}

}

[/php]

After you have supplemented those code and function and installed MGS_Wishlist module to your Magento website, you are obviously able to Add (product) to cart or Add all items to shopping cart from the sharing wishlist via email without any errors. Why hesitate to share your favorite products to your friends now?
We believe there are still some other practical tips and hints to fix the issue raised in this article. For the benefit of Magento developers, we are proud to share our knowledge and we hope to receive your valuable comments then. Thanks for reading.

Download example here

Besides, if you are looking out for a cost effective Magento package for your eCommerce store, then look nowhere other than Magesolution. We not only offer an affordable Magento Development Package for all size and budget but also ensure that it helps your online business grow and sustain. Contact us for a free consultation!