Magento 2 Disable Shipping Method Based on Total
-
14-04-2021 - |
Question
I created a custom shipping module and I want to disable it at checkout if the total is less than 100. I created an Observer called DisablePayment.php:
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class DisablePayment implements ObserverInterface
{
public function execute( Observer $observer )
{
$result = $observer->getEvent()->getResult();
$method_instance = $observer->getEvent()->getMethodInstance()->getCode();
$quote = $observer->getEvent()->getQuote();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cartObj = $objectManager->get('\Magento\Checkout\Model\Cart');
$grandTotal = $cartObj->getQuote()->getGrandTotal();
if($method_instance == 'methodcode')
{
$checkoutLimit = 100;
$total = $grandTotal;
if($checkoutLimit > $total)
{
$result->setData('is_available', false);
}
}
}
}
I can't get this to work. Do I need to do anything else?
Thanks, Stan
La solution
In your custom shipping method module. there is a model defined in app/code/vendorname/packagename/etc/config.xml
In your custom shipping model file add below code.
<?php
namespace Stackoverflow\Customshipping\Model\Carrier;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;
class Custom extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
\Magento\Shipping\Model\Carrier\CarrierInterface
{
......
......
......
protected $cart;
public function __construct(
......
......
\Magento\Checkout\Model\Cart $cart,
......
......
) {
......
$this->cart = $cart;
......
}
/**
* {@inheritdoc}
*/
public function collectRates(RateRequest $request)
{
......
......
$subTotal = $this->cart->getQuote()->getSubtotal();
if($subTotal < 100){
return false;
}
......
......
}
......
......
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange