Overriding Quote Item Weight Programatically

by Tryingest Fool   Last Updated March 14, 2019 17:09 PM

My goal is to alter the weight of a product based on a chosen custom option. I have the custom option part working, but am unable to alter the weight of the item is such a way that affects the shipping estimates.

The below code partly works, in that it initially sets the correctly updated weight in the quote_item table. However, this gets overwritten, and is always overwritten before shipping is calculated. Is there a better way to do this? Or should I be plugging in later, perhaps? Any thoughts would be greatly appreciated!


namespace Ibex\Options\Model\Plugin;

use Magento\Quote\Model\Quote;

class Weight
    protected $configurationHelper;

    public function __construct(
        \Magento\Catalog\Helper\Product\Configuration $configurationHelper
        $this->configurationHelper = $configurationHelper;

    public function beforeSetProduct(\Magento\Quote\Model\Quote\Item $subject, $product)
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');

        $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])){
                    $itemOption = $subject->getOptionByCode('option_'.$optionId);

                    $group = $option->groupFactory($option->getType())

                        $optionValue = $group->getOption()->getValueById($itemOption->getValue());
                        $selectedWeight = $optionValue->getCustomWeight();
        $weight = $product->getWeight();
          $newWeight = $weight + $selectedWeight;
        return [$product];

Related Questions

Updated March 20, 2017 09:09 AM

Updated April 28, 2017 06:09 AM

Updated March 15, 2016 08:03 AM

Updated February 20, 2017 06:09 AM

Updated February 20, 2017 12:09 PM