Magento – Redirect to same product URL after error from Add To Cart

cartproductredirect

Overview:

On my product called Test Product has 10 quantity.

enter image description here

So when I put 40 quantity and press add to cart. (Remember, the quantity of the product is 10, so it should prompt an error)

enter image description here

The output is correct, the user got notified by the system that they put greater than the quantity than the actual quantity of the product.

enter image description here

If you look at the URL closely, before the user click the add to cart, the URL is

enter image description here

When the error has been shown, the URL is

enter image description here

Meaning, magento removes the category link and redirects to the actual product link.

Question
Is there any way for magento to redirect to the current category instead of the product link?

Best Answer

You would need to write an extension that adds a good bit of info that isn't passed by default. There's no Magento setting that would achieve this.

If you look at the addProduct function in app\code\Core\Mage\Checkout\Model\Cart.php, the $requestInfo only includes the product id, which in turn is used later on the get the url that you are returned to. There's no way of Magento knowing which category you're coming from because the only thing passed in the product id.

Inside of that function you will see a comment stating "String we can get if prepare process has error". The code right below this is where the redirect url is generated using $product->getUrlModel()->getUrl..

There are several ways you could extend this to get the result you want. One way would be to get the first category for the product and change the way the $redirectUrl is generated so that it always includes that category.

Another method might be to pass along the referer url that's available in the initial request which would be located in the addAction function in app\code\core\Mage\Checkout\controllers\CartController.php. You could add it as part of the params that gets passed to the addProduct function in the Model. The referer url will have the category as part of the url.

Related Topic