I have followed this example magento: URL querystring for adding product and applying discount coupon to cart to add products to cart and apply discounts at the same time using 1 request.
It works fine except for the first request (ex: in incognito mode) as it will give a 404 not found and then if I refresh the URL again it will work just fine.
The URL looks like this
I believe this comes from the fact that the session is not initialized at the moment of the request so I tried to add a redirect in the code but it is not working and also it does not seem like the brightest idea.
This is the code that adds the cart function
require_once 'Mage/Checkout/controllers/CartController.php';
class Namespace_AddProductFromUrl_Checkout_CartController extends Mage_Checkout_CartController {
# overloaded addAction
public function addAction()
{
// generate form_key if missing or invalid
if ( ! ($formKey = $this->getRequest()->getParam('form_key', null)) or $formKey != Mage::getSingleton('core/session')->getFormKey())
{
$this->getRequest()->setParams(array('form_key' => Mage::getSingleton('core/session')->getFormKey()));
}
// do parent actions
parent::addAction();
}
}
What I tried so far is to add a redirect in the main if:
$this->getRequest()->setParams(array('form_key' => Mage::getSingleton('core/session')->getFormKey()));
$this->_redirect($this->getRequest()->getRequestUri());