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 :


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;       

public function execute()

    try {
        $_product = $this->_productRepository->getById(1);
        //$_product = $this->_productRepository->get('sku1');

        $params = array();
        $params['qty'] = 1;

        $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


Solution (if we know option id) :

        $param = array(
            'product' => $_product->getId(),
            'qty' => 1,
            'options' => array(
                0 => 'ABC',
                1 => 'DEF'

EDIT 1 : To be able to get the options id :

private function getOptionIdByTitle($title, $_product){
    $result = 0;
    foreach ($_product->getOptions() as $option) {
        if($title == $option->getTitle())
            $result = $option->getId();
    return $result;


$myOptionId = $this->getOptionIdByTitle('my_option', $_product);

$params = array(
   'product' => $_product->getId(),
   'qty' => 1,
   'price' => $_product->getPrice(),
   'options' => array(
     $myOptionId => 'ABC'

EDIT 2 :

Due to this issue : "Unable to set different custom option labels for multiple store views" : https://github.com/magento/magento2/issues/5885

It seems very complicated to manage/retrieve options ids for multiple products... Retrieving by title is a bad idea as it is supposed to change depending on store views...

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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