Pregunta

I have a simple shipping method implemented by this tutorial: https://www.mageplaza.com/devdocs/magento-2-create-shipping-method/

I added the Max Weight field

<field id="max_weight" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
    <label>Max Weight</label>
    <validate>validate-number validate-zero-or-greater</validate>
</field>

I need to write logic that will calculate the total weight of all added products and if it exceeds 20kg then return false

I see this logic as the weight multiplied by the number of products, I found the number of products but I cannot find the weight, tell me how to do it as much as possible correctly

public function collectRates(\Magento\Quote\Model\Quote\Address\RateRequest $request)
{
    $qty = 0;
    if ($request->getAllItems()) {
        foreach ($request->getAllItems() as $item) {
            if ($item->getProduct()->isVirtual()) {
                continue;
            }

            if ($item->getHasChildren()) {
                foreach ($item->getChildren() as $child) {
                    if (!$child->getProduct()->isVirtual()) {
                        $qty += $child->getQty();
                    }
                }
            } else {
                $qty += $item->getQty();
            }
        }
    }

    if($productsWeight > getShippingWeight()) {
        return false;
    }
    return parent::collectRates($request);
}
¿Fue útil?

Solución

Try the following way:


if($request->getPackageWeight() > $this->getConfigData('max_weight')) {
    return false;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top