How to check if the weight of the product is more than 20 kg
-
14-04-2021 - |
题
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);
}
解决方案
Try the following way:
if($request->getPackageWeight() > $this->getConfigData('max_weight')) {
return false;
}