0

How can we save the variation of a configurable product dynamically ? Please Help me.

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 the below ids as configurable options for example purposes 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();

2 Answers 2

0

Check the below code.

Send below the object to add the product.

$objParam = new \Magento\Framework\DataObject(
        [
            'product' => $product->getId(), //configurable product id
            'selected_configurable_option' => $childid, //selected simple product id
            'qty' => $item['qty'],
            'super_attribute' => $attributes
        ]
    );

update our code as per your requirement.

   //create configurable product order
if ($productType == 'configurable') {
    $searchCriteria = $this->searchCriteriaBuilder
        ->addFilter('order_id', $orderId)
        ->addFilter('parent_item_id', $item['order_item_id'])
        ->create();

    $ordersItemList = $this->orderItemRepository->getList($searchCriteria);

    foreach ($ordersItemList as $itemchild) {
        $childid = $itemchild->getProductId();
        $ItemId = $itemchild->getItemId();
        if ($itemchild->getProductType() == 'simple') {
            $attributes = $itemchild->getProductOptions()['info_buyRequest']['super_attribute'];
        }
    }
    $objParam = new \Magento\Framework\DataObject(
        [
            'product' => $product->getId(), //configurable product id
            'selected_configurable_option' => $childid, //selected simple product id
            'qty' => $item['qty'],
            'super_attribute' => $attributes
        ]
    );
}

$this->cart->addProduct($product, $objParam);
$this->_cart->save();
4
  • bro i want to save the values in cart not in order can you advise me according the product cart Thanks
    – moazzams
    Commented Dec 23, 2021 at 9:09
  • above code is only used for products save into the cart
    – Devidas
    Commented Dec 23, 2021 at 9:19
  • $objParam = new \Magento\Framework\DataObject( [ 'product' => $product->getId(), //configurable product id 'selected_configurable_option' => $childid, //selected simple product id 'qty' => $item['qty'], 'super_attribute' => $attributes ] );
    – Devidas
    Commented Dec 23, 2021 at 9:20
  • Send above the object to add the product into cart.
    – Devidas
    Commented Dec 23, 2021 at 9:20
0

here is my code which i am using can you edit for configurable

<?php

namespace Greenplank\Addtocart\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action {

/**
 * @var \Magento\Checkout\Model\Cart
 */
protected $cart;
protected $product;
protected $resultFactory;
protected $productRepository;
protected $formKey;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Controller\ResultFactory $resultFactory,
    \Magento\Catalog\Model\Product $product,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Framework\Data\Form\FormKey $formKey,
    // \Magento\Catalog\Model\ProductFactory $_productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    $this->resultFactory = $resultFactory;
    $this->cart = $cart;
    $this->product = $product;
    $this->productRepository = $productRepository;
    $this->formKey = $formKey;
    // $this->productFactory = $_productFactory;
    parent::__construct($context);
}
public function execute()
{
      // if (!$this->_formKeyValidator->validate($this->getRequest())) {
      //       return $this->resultRedirectFactory->create()->setPath('*/*/');
      //   }
    
    try {
        $params = array();
        // $params['qty'] = '1';//product quantity
        $skuId =$_GET['sku'];
        $_product = $this->productRepository->get($skuId);
        $qty= $this->getRequest()->getParam('qty');
        // $options = array(
        //     93 => 992,
        //     194 => 984
        // );
        $params=array(
           'form_key' => $this->formKey->getFormKey(),
           // 'super_attribute' => $options, 
           'qty'=> $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;
        if ($_product){
            $this->cart->addProduct($_product, $params);
            $this->cart->save();
        }
        // /*cart page*/
        //  $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        // // Your code
        // $resultRedirect->setUrl("/checkout/cart");
        // return $resultRedirect;

        $this->messageManager->addSuccess(__('Lägg i kundvagnen framgångsrikt.'));
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->messageManager->addException(
            $e,
            __('%1', $e->getMessage())
        );
    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('error.'));
   }
    $this->getResponse()->setRedirect('/checkout/cart/');       
 }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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