Question

I'm trying to modify the weight of a product depending which custom options are selected. At the moment, I have a Plugin for Magento\Quote\Model\Quote\Weight with this function:

public function beforeSetProduct(\Magento\Quote\Model\Quote\Item $subject, $product) {}

..In which I can get/set the product weight successfully. At this point, though, I need to grab the weight from the selected customizable option and am at loss on how to do that. Any thoughts/ideas would be appreciated.

Was it helpful?

Solution

Add the following code in your plugin function and you will get the selected option value (I assume you have a drop down option and you identify the value of your custom weight by the label of the choosen option). You can find some explanation of what's going on in the comments. You only need to change the title of your custom option in the code.

$customOptions = $product->getCustomOptions();

if (isset($customOptions['option_ids'])){
    $optionIds = $customOptions['option_ids'];

    foreach (explode(',', $optionIds->getValue()) as $optionId) {
        $option = $product->getOptionById($optionId);
        if (isset($customOptions['option_'.$optionId])){

            //load the corrsponding quote item option object fo the given id
            $itemOption = $subject->getOptionByCode('option_'.$optionId);

            //create a model of the type of this option and load the data for the selected option value
            $group = $option->groupFactory($option->getType())
            ->setOption($option)
            ->setConfigurationItem($subject)
            ->setConfigurationItemOption($itemOption);

            //change here with the title of your custom option
            if ($option->getTitle() == "your_custom_weight_title"){
                //get the selected value, e.g. the label for drop down options
                $selectedWeightValue = $group->getPrintableOptionValue($itemOption->getValue());
            }
            //get the order value object to access it's data like price or sku
            $optionValue = $group->getOption()->getValueById($itemOption->getValue());
            $sku = $optionValue->getSku();
            $price = $optionValue->getPrice();
        } 
    }
}

OTHER TIPS

Much simpler:

$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top