skip to Main Content

I tried to add product programmatically. and i use below code

$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$paramater = array(
            'product' => $product->getId(),
            'related_product' => null,
            'qty' => 1,
            'form_key' => Mage::getSingleton('core/session')->getFormKey()
        );
$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

This code is working fine after login. but before login i am getting following error.

a:5:{i:0;s:640:”SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (db_magento_nua.sales_flat_quote_item, CONSTRAINT FK_SALES_FLAT_QUOTE_ITEM_QUOTE_ID_SALES_FLAT_QUOTE_ENTITY_ID FOREIGN KEY (quote_id) REFERENCES sales_flat_quote (entity_id) ON DELE), query was: INSERT INTO sales_flat_quote_item (created_at, updated_at, product_id, store_id, is_virtual, sku, name, is_qty_decimal, weight, qty, custom_price, product_type, original_custom_price, base_cost) VALUES (‘2019-06-11 12:17:58’, ‘2019-06-11 12:17:58’, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)”;i:1;s:2586:”#0 /var/www/html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)

Can some one help me to fix the issue. Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I find a solution for this. since there is no quote i am not able to add item. i just need to initiate quote before adding product to cart. i use below code to adding a product now.

     $cart = Mage::getSingleton('checkout/cart');
     $cart->init();
     $quote = $cart->getQuote();
     $paramater = array(
        'product' => $product->getId(),
        'qty' => 1,
        'form_key' => Mage::getSingleton('core/session')->getFormKey()
     ); 
     $request = new Varien_Object();
     $request->setData($paramater);
     $quote->addProduct($product, $request);
     $quote->save();
     $cart->save();
    
    

    Above code works as expected.


  2. Try using Mage::getModel()

    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $paramater = array(
                    'product' => $product->getId(),
                    'related_product' => null,
                    'qty' => 1,
                    'form_key' => Mage::getSingleton('core/session')->getFormKey()
                );
    $request = new Varien_Object();
    $request->setData($paramater);
    $cart->addProduct($product, $request);
    $cart->save();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search