1

I had to create a controller that added or removed an option from a quote item.

I succeeded but did not convince the solution. It seems strange to me that I have to manage the correct populating of the option: "option_ids". Can someone with experience tell me if there is a better solution?

// Add o remove optional.
$optionId = 1234; // Id optional.
$optionData = $product->getOptionByid($optionId);
foreach ($optionData->getValues() as $v) {
    $optionId = $v->getOptionId();
    $optionCode = 'option_' . $optionId;
    $itemOptionIds = $quoteItem->getOptionByCode('option_ids');

    if ($status) {
        $quoteItem->addOption(new Varien_Object([
          'product' => $quoteItem->getProduct(),
          'code' => $optionCode,
          'value' => $v->getOptionTypeId()
          ])
        );

        if ($itemOptionIds) {
            $optionIds = explode(',', $itemOptionIds->getValue());
            $optionIds[] = $optionId;
            $quoteItem->getOptionByCode('option_ids')->setValue(implode(',', $optionIds));
        } else {
            $quoteItem->addOption(new Varien_Object([
                'product' => $quoteItem->getProduct(),
                'code' => 'option_ids',
                'value' => $optionId
              ])
            );
        }
    } else {
        $optionIds = [];
        if ($itemOptionIds) {
            foreach (explode(',', $itemOptionIds->getValue()) as $itemOptionId) {
                if ($optionId === $itemOptionId) {
                    $quoteItem->removeOption('option_' . $optionId);
                } else {
                    $optionIds[] = $itemOptionId;
                }
            }

            if (!empty($optionIds)) {
                $quoteItem->getOptionByCode('option_ids')->setValue(implode(',', $optionIds));
            } else {
                $quoteItem->removeOption('option_ids');
            }
        }
    }

    $quoteItem->setDataChanges(true);
    $quoteItem->save();
}

// Save cart.
$this->_getCart()->save();

Your Answer

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

Browse other questions tagged or ask your own question.