3

This question already has an answer here:

Magento2 how to add the configurable product to cart programmatically. I searched but found question related to how add simple product mostly.

marked as duplicate by sv3n, Jai, Priyank, Keyur Shah, Prince Patel Feb 4 '18 at 7:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Why downvote this question? It's not duplicate with any previous questions and maybe needed by developers in the future. – PY Yick Jul 11 '17 at 4:07
  • not duplicate? magento.stackexchange.com/… – LucScu Jul 11 '17 at 7:14
3

Process of adding configurable product to cart

//Get cart object
$cart = $this->_objectManager->get('Magento\Checkout\Model\Cart');
// Load Configurable Product
$productId = 10;//configurable product id
$product = $this->_objectManager->create('Magento\Catalog\Model\ProductFactory')->create()->load($productId);

// load child product
$childId = 11;
$childProduct = $this->_objectManager->create('Magento\Catalog\Model\ProductFactory')->create()->load($childId);

/* Prepare cart params */
$params = [];
$params['product'] = $product->getId();
$params['qty'] = $item['qty'];
$options = [];


$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);

foreach($productAttributeOptions as $option){
    $options[$option['attribute_id']] =  $childProduct->getData($option['attribute_code']);
}
$params['super_attribute'] = $options;

/*Add product to cart */
$cart->addProduct($product, $params);
$cart->save();
  • where comes the $productAttributeOptions var from? – Gordon Freeman Jan 23 at 15:31
  • @GordonFreeman sorry i missed that variable. added the variable in the post. – satya prakash patel Jan 24 at 7:47
  • I did some research in the meantime and could find what you meant, but anyways .. take that +1 – Gordon Freeman Jan 24 at 8:29
  • above code is not working for me still given the same error You need to choose options for your item. – Narayan Mar 5 at 7:01
0

for Adding Configurable product into cart, you don't have to do anything fancy.

just hit the Magento\Checkout\Controller\Cart\Add class with specific form data.

below is the form format which you will post to the Magento\Checkout\Controller\Cart\Add controller.

<form class="add-tocart-form" action="http://baseurl/checkout/cart/add/uenc/aHR0cDovLzEyNy4wLjAuMS9uZXN0by9jb29sb3IuaHRtbA%2C%2C/product/11/" method="post" id="product_addtocart_form" novalidate="novalidate">
<input type="hidden" name="product" value="11">
<input type="hidden" name="selected_configurable_option" value="<?= $selectedProductId?>">
<input name="form_key" type="hidden" value="tJ8DBPxf8HTxBrpT">                                    
            <div class="product-options-wrapper" id="product-options-wrapper" data-hasrequired="* Required Fields">
<div class="fieldset" tabindex="0">
  <div class="field configurable required">
      <label class="label" for="attribute93">
          <span><= $attributeLabel></span>
      </label>
      <div class="control">
          <select name="super_attribute[<= $attributeId>]"  data-validate="{required:true}" class="super-attribute-select" aria-required="true">
<option value="">Choose an Option...</option>
<option value="<?= $optionId1?>"><?= $optionLabel1?></option>
<option value="<?= $optionId2?>"><?= $optionLabel2?><</option></select>
      </div>
  </div>
</div>
</form>
<!--add this part as it will handle the ajax add to cart if needed-->

<script type="text/x-magento-init">
    {
        ".add-tocart-form": {
            "catalogAddToCart": {}
        }
    }
</script>

with above method you dont need to update the minicart manually it magento updated all the required content so minicart will be updated automatically.

for reference you can refer the configurable product form format (in product view) is should be same as in product page.

Hope this help.

Note: Since Magento\Checkout\Model\Cart is deprecated you should avoid using it.

-1

Here I am using the example of color and size attributes.

protected $_cart;
protected $productRepository;

public function __construct(
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
)
{
    $this->_cart = $cart;
    $this->productRepository = $productRepository;
}

...
...

$productId = 10; // enter your product_id
$qty = 1; // enter number of quantites you want to add

/*
I am using below ids as configurable options for example purpose only.
You have to use your attribute id and option id.

90 = attribute_id of color 
53 = option_id of any specific color,

143 = attribute_id of size
170 = option_id of any specific size
*/

$options = array(
                90 => 53,
                143 => 170
            );

$params = array(
    'product' => $productId,
    'super_attribute' => $options,
    'qty' => $qty
);

$_product = $this->productRepository->getById($productId);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();

Note: Programatically added product to cart will not be visible in minicart. Check your added products in shopping cart page. If you want to update your minicart after adding product programatically, Please visit below link

https://webkul.com/blog/update-cart-adding-product-programmatically-magento2/

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