Pregunta

I want to add to cart product with custom options. I added simple product, but can't able to add with custom options.

How to do it ?

Please help me.

Thanks.

¿Fue útil?

Solución

Try to use this code in your controller. It's for specific product. If you want to add multiple products. Then, you need to save multiple product collection in $product variable.

protected $formKey;
protected $_productFactory;
protected $_cart;
protected $messageManager;
protected $_url;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Framework\UrlInterface $url,
    \Magento\Framework\Message\ManagerInterface $managerInterface,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    parent::__construct($context);
    $this->formKey = $formKey;
    $this->_url = $url;
    $this->messageManager = $managerInterface;
    $this->_productFactory = $productFactory;
    $this->_cart = $cart;
}

public function execute()
{
    $product = $this->_productFactory->create()->load($productID);
    if ($product) {
        foreach ($product as $key => $value) {
            $custom_option_value = '';
            if (isset($value['super_attribute']) || !empty($value['super_attribute'])) {
                $custom_option_value = $value['super_attribute'];
            }
            $this->addCartProduct($value['id'], $value['qty'], $custom_option_value,$product);
        }
        $this->_cart->save();
    }
    $this->messageManager->addSuccess('Shopping cart updated succesfully.');
}

public function addCartProduct($productID, $productQty, $custom_option_val,$product)
{
    $info = new \Magento\Framework\DataObject(
        [
            'form_key' => $this->formKey->getFormKey(),
            'product_id' => $productID,
            'qty' => $productQty,
            'super_attribute' => $custom_option_val
        ]
    );
    return $this->_cart->addProduct($product, $info);
}

Hope, It will helpful for you.

Otros consejos

add products to cart with customizable options


$product = $productFactory->create();
$product->setStoreId(1)->load($product->getIdBySku($sku));
$params = new \Magento\Framework\DataObject();
$params->setQty($qty);
foreach ($product->getOptions() as $o) {
foreach ($o->getValues() as $value) {
if ($value["sku"] == 'RED') { //add this if to search for your custom option by sku or the value name etc.
$options[$value['option_id']] = $value['option_type_ id'];
$params->setOptions($options); //set the customizable option to the product

}
}
}
try {
$quote1->addProduct($product, $params); //add to cart 🙂
} catch (Exception $e) {echo $e->getMessage();}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top