Search code examples
phpmagento

Programatically adding product to magento cart not working at the first time only


I'm creating custom functions for sign up and adding product to customer cart.

If user signed up using my function first product that he/she added will not be added to the cart unless he added another product after that everything working perfect and the first product also appear in the cart.

If user signed up by using magento sign up form then used my function to add product to the cart everything working.

Sign up code

public function signupAction() {
    $email = $this->getRequest()->getPost('email');
    $password = $this->getRequest()->getPost('password');
    $firstName = $this->getRequest()->getPost('firstName');
    $LastName = $this->getRequest()->getPost('LastName');

    $session = Mage::getSingleton('customer/session');
    $session->setEscapeMessages(true);
    $websiteId = Mage::app()->getWebsite()->getId();
    $store = Mage::app()->getStore();
    $customer = Mage::getModel("customer/customer");
    $customer->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname($firstName)
            ->setLastname($LastName)
            ->setEmail($email)
            ->setPassword($password);
    try {
        $customer->cleanPasswordsValidationData();
        $customer->save();
        $this->_dispatchRegisterSuccess($customer);
        $this->_successProcessRegistration($customer);
    } catch (Mage_Core_Exception $e) {

    } catch (Exception $e) {

    }
}

Add to cart code

public function addAction() {
    $form_key = Mage::getSingleton('core/session')->getFormKey();
    $json = $this->getRequest()->getPost('json');
    $jsonObj = json_decode($json);
    $cart = $this->_getCart();
    $cart->init();
    $response = array();
    try {
        foreach ($jsonObj as $data) {
            $param = ['form_key' => $form_key,
 'qty' => $data->qty, 'product' => $data->productId];
            $product = $this->_initProduct($param['product']);
            if ($data->type == 'simple') {
                $cart->addProduct($product, $param);
            }
        }
        $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()) {
            $response['status'] = 'SUCCESS';
        } else {
            $response['status'] = 'Error';
        }
    } 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 items.');
        Mage::logException($e);
    }
    $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
    return;
}

Solution

  • refresh the page is solution because magento use the form key to validate the data

    so when login a customer then session is change according to that and it working

    let me know if you have more Questions .