set shipping method from observer based on subtotal
-
20-10-2020 - |
Domanda
I am trying set shipping method based on subtotal from cart page. If subtotal is less than certain amount then customer will have Flat rate as shipping method else it will be free shipping.
Soluzione
One approach can be filtering of shipping methods based on sub-total. This way you can activate or deactivate required shipping methods.
For filtering shipping methods:
1> Rewrite the shipping model class: Mage_Shipping_Model_Shipping
File: app/code/local/MagePsycho/Shipmentfilter/etc/config.xml
Code:
...
<global>
...
<models>
<shipping>
<rewrite>
<shipping>MagePsycho_Shipmentfilter_Model_Shipping</shipping>
</rewrite>
</shipping>
</models>
...
</global>
2> Override the method: collectCarrierRates()
File: app/code/local/MagePsycho/Shipmentfilter/Model/Shipping.php
Code:
<?php
/**
* @category MagePsycho
* @package MagePsycho_Shipmentfilter
* @author magepsycho@gmail.com
* @website http://www.magepsycho.com
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class MagePsycho_Shipmentfilter_Model_Shipping extends Mage_Shipping_Model_Shipping
{
public function collectCarrierRates($carrierCode, $request)
{
if (!$this->_checkCarrierAvailability($carrierCode, $request)) {
return $this;
}
return parent::collectCarrierRates($carrierCode, $request);
}
protected function _checkCarrierAvailability($carrierCode, $request = null)
{
$subtotal = Mage::getSingleton('checkout/session')->getQuote()->getSubtotal();
$amountToCheck = 250; //Edit this amount
if ($subtotal > $amountToCheck) {
if($carrierCode == 'flatrate'){ #Hide Flat Rate
return false;
}
}
return true;
}
}
Altri suggerimenti
This is what I have done.
<?php
class Infoway_Shipping_Model_Shipping extends Mage_Shipping_Model_Shipping {
public function collectCarrierRates($carrierCode, $request) {
if (!$this->_isAvailable($carrierCode, $request)) {
return $this;
}
return parent::collectCarrierRates($carrierCode, $request);
}
/**
* @param string $carrierCode
* @param Varien_Object $request
* @return bool
*/
protected function _isAvailable($carrierCode, $request) {
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals();
//setting shipping on subtotal
$subtotal = $totals["subtotal"]->getValue();
$min_order_amount = Mage::getStoreConfig('carriers/freeshipping/free_shipping_subtotal');
//conversion of base currency to store currency
$rate = Mage::app()->getStore()->getCurrentCurrencyRate();
$min_order_amount = $min_order_amount * $rate;
switch ($carrierCode) {
case 'flatrate':
if ($subtotal >= $min_order_amount) {
return false;
}
break;
case 'freeshipping':
if ($subtotal < $min_order_amount) {
return false;
}
break;
}
return true;
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange