1

I want to add a configurable products to cart via ajax, for this I have tried below code but it always raised the error “You need to choose options for your item”.

Code

public function execute() {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $quote = $objectManager->get('\Magento\Checkout\Model\Cart');
        $productId = 20318;
        $product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);

        $cart = $objectManager->create('Magento\Checkout\Model\Cart');
        $params = array();

        $options = array(
            "194" => "445",
            "202" => "447",
            "193" => "416",
            "201" => "439",
            "197" => "430",
            "196" => "427",
        );
        $params['qty'] = 1;
        $params['product'] = 20318;

        $params['super_attribute'] = $options;


        $cart->addProduct($product, $params);
        $cart->save();
    }

Can anyone please let me know whats the issue?

I have also tried the below code but it raised the same error. https://magento.stackexchange.com/a/198818/38685 https://magento.stackexchange.com/a/183836/38685

  • do not use the objectmanager it's bad practice – Philipp Sander Mar 5 at 8:18
  • @PhilippSander okay I will remove that. but can you please let me know whats wrong in my error and how to solve this error? – Narayan Mar 5 at 8:33
  • please try building the options array with ints instead of strings – Philipp Sander Mar 5 at 8:34
  • we don't know the product. maybe there's actually an option missing – Philipp Sander Mar 5 at 8:37
  • @PhilippSander I have tried this too but same error – Narayan Mar 5 at 8:37

Your Answer

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

Browse other questions tagged or ask your own question.