7

I'm adding a nominal product programically to the shopping cart. But it throws an exception as 'The stock item for Product is not valid.'. How can I resolve this?

NOTE : $product is getting passed to this function correctly.

My code is as follows.

    /**
     * Add air product to the cart.
     */
    public function addSubscriptionToCart($product)
    {
        try {
            // Create cart instance.
            $cart = Mage::getModel('checkout/cart');

            // Initialize the cart.
            $cart->init();
            $cart->addProduct($product, array('product_id' => $product->getId(), 'qty' => 1)); // This line causes the error.
            $cart->save();

            return true;

        } catch(Exception $e) {
            Mage::log($e->getMessage());
            return false;
        }
    }
13

solved!, Instead of the product object pass product ID to addProduct() method worked. See the corrected code below.

    /**
     * Add air product to the cart.
     */
    public function addSubscriptionToCart($product)
    {
        try {
            // Create cart instance.
            $cart = Mage::getModel('checkout/cart');

            // Initialize the cart.
            $cart->init();
            $cart->addProduct($product->getId()); // pass product ID
            $cart->save();

            return true;

        } catch(Exception $e) {
            Mage::log($e->getMessage());
            return false;
        }
    }
  • Fatal error: Uncaught TypeError: Argument 1 passed to Mage_Sales_Model_Quote::addProduct() must be an instance of Mage_Catalog_Model_Product, string given, called in – OZZIE Feb 7 '18 at 9:11
1

I had the same issue. But i was using another code for adding to the cart:

$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->addProduct($_product, 1);
$quote->collectTotals()->save();

And my problem was in wrong product object. I was loading it by attribute "sku":

Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

When i changed it to simple load

Mage::getModel('catalog/product')->load($id);

then error was resolved.

So problem was in "wrong" product object by loadByAttribute function.

  • Oh, this was my issue, too! Thanks for the clarification :3 – Keenora Fluffball May 7 '18 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.