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!

<?php

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())
                    ->setOption($option)
                    ->setConfigurationItem($subject)
                    ->setConfigurationItemOption($itemOption);

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


Related Questions




Get cart contents from my custom module

Updated March 15, 2016 08:03 AM

Magento 1.9 Not able to create quote item

Updated February 20, 2017 06:09 AM