I've already seen this post, but cannot use it : How to create order programmatically in Magento 2?
I would like to be able to programmatically add products to cart, and I need to set 'Customizable Options' that are textfields and datefield.
I'm lost into the Magento 2 core code, and keep getting errors.
The main one actually is : "Please specify product's required option(s)."
I tried using 'Magento\Catalog\Model\Product\Option', but I cannot build my options array properly.
Here is my actual code :
<?php
namespace Company\Module\Controller\Post;
use Magento\Framework\App\Action\Action;
use Magento\Catalog\Api\ProductRepositoryInterface;
class Checkout extends Action {
protected $_cart;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Checkout\Model\Cart $cart
/* ... here some stuff ... */
$this->_cart = $cart;
parent::__construct($context);
}
public function execute()
{
try {
$_product = $this->_productRepository->getById(1);
//$_product = $this->_productRepository->get('sku1');
$params = array();
$params['qty'] = 1;
$this->_cart->addProduct($_product,$params);
$this->_cart->save();
$this->_redirect("checkout/cart/add/form_key/", $params);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addException($e, __('%1', $e->getMessage()));
} catch (\Exception $e) {
$this->messageManager->addException($e, __('error.'));
}
}
}
This function is executed on a form submit