I cannot programmatically add a vitrual product to the cart with my custom options to the cart. I have a code in the observer that adds a product, but if it is a product with its custom options, it does not add to the cart, after clicking add to cart, it only transfers to this product and tells you to choose an option. Ive tried in different ways, but I do not succeed. Maybe someone will help. I have this code.
protected $_productRepository;
protected $_cart;
protected $formKey;
public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Checkout\Model\Cart $cart, \Magento\Framework\Data\Form\FormKey $formKey){
$this->_productRepository = $productRepository;
$this->_cart = $cart;
$this->formKey = $formKey;
}
public function execute(EventObserver $observer)
{
$product_id = 2110;
$item = $observer->getEvent()->getData("quote_item");
$product = $observer->getEvent()->getData("product");
if($product->getId() != $product_id){
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product' => $product_id,
'qty' => 1,
"product_option" => array(
"extension_attributes" => array(
"custom_options" => array(
"option_type_id": 1387,
)
)
)
);
$_product = $this->_productRepository->getById($product_id);
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
$this->_cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
}
This code does not add to cart, of course. I do not know how I can add know the id of a virtual product and add it with the options selected after the SKU.