How to Enable Shipping Method via Observer in Magento 2

event-observershipping-methods

Lets say I want to check what shipping methods are available (before customer sees the shipping methods) and want to enable one if certain conditions exist.

  • What event would I be observing
  • What method calls do I need:

    1. To see what shipping methods are enabled
    2. To enable a given shipping method

Best Answer

Magento shipping method is depends on shipping address . first load quote shipping address then get shipping method from shipping address and code should like this

 $quoteShippingAddress = $quote->getShippingAddress();
        if(!is_null($quoteShippingAddress->getId()) ) {

 $quoteShippingAddress->collectShippingRates()->save();
     $groupedRates = $quoteShippingAddress->getGroupedAllShippingRates();
            $ratesResult = array();
            foreach ($groupedRates as $carrierCode => $rates ) {
                $carrierName = $carrierCode;
                if (!is_null(Mage::getStoreConfig('carriers/'.$carrierCode.'/title'))) {
                    $carrierName = Mage::getStoreConfig('carriers/'.$carrierCode.'/title');
                }

                foreach ($rates as $rate) {
                    $rateItem = $this->_getAttributes($rate, "quote_shipping_rate");
                    $rateItem['carrierName'] = $carrierName;
                    $ratesResult[] = $rateItem;
                    unset($rateItem);
                }
            }

}

$result is give shipping method list

2.As amasty say,shipping method are enabled from admin.Also you can do this by programmatically:

 $groups=array();
shippimgmethodcode='freeshipping';
$groups[$shippimgmethodcode][fields][active][value]=true;
Mage::getModel('adminhtml/config_data')
    ->setSection('carriers')
    ->setWebsite(null)
    ->setStore($StoreId)
    ->setGroups($groups)
    ->save(); 
Related Topic