2

I'm creating an order via code, more or less along the lines of How to create order programmatically in Magento 2?.

But I don't find a way to set a customizable option, that already exists on the product, by code. How to do it?

1
  • You want to set the custom options for order? Commented Feb 10, 2017 at 0:39

1 Answer 1

1

To answer my on question, you can set the option on the \Magento\Quote\Model\Quote\Item item:

private function setOptionValue($product, $item, $optionTitle, $valueTitle)
{
    $option = $this->getOption($product, $optionTitle);
    $value = $this->getValue($option, $valueTitle);

    if (!$value) {
        throw new \Exception("Value \"$valueTitle\" could not be set for option \"{$option->getTitle()}\" for product {$product->getId()}");
    }

    $item->addOption(
        $this->option->create()
            ->setCode('option_'.$option->getId())
            ->setProductId($product->getId())
            ->setValue($value->getId())
    );

    $item->addOption(
        $this->option->create()
            ->setCode('option_ids')
            ->setProductId($product->getId())
            ->setValue($option->getId())
    );
}

private function getOption($product, $title)
{
    foreach ($product->getOptions() as $option) {
        if ($option->getTitle() == $title) {
            return $option;
        }
    }
}

private function getValue($option, $title)
{
    foreach ($option->getValues() as $value) {;
        if ($value->getTitle() == $title) {
            return $value;
        }
    }
}

The second add option block somehow does the trick. It add an entry to the quote_item_option table containing the code "option_ids" and the option IDs as value.

Can be done with arrays only also:

       $item->setOptions([
           ['product_id'=>299, 'code'=>'option_4', 'value'=>'10'],
          ['product_id'=>299, 'code'=>'option_ids', 'value'=>4]
       ]);

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.