Skip to content

Instantly share code, notes, and snippets.

@herveguetin
Last active October 17, 2017 07:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save herveguetin/11123309 to your computer and use it in GitHub Desktop.
Save herveguetin/11123309 to your computer and use it in GitHub Desktop.
Set shipping method and rate if they do not exist yet in Magento
<?php
/**
* Has shipping been applied to quote?
*
* @var bool
*/
protected $_hasShipping = false;
/**
* Set shipping method and rate if they do not exist yet
*/
public function setQuoteShippingMethod()
{
if(!$this->_hasShipping) {
$this->_hasShipping = true; // This is to avoid loops on totals collecting
$quote = Mage::helper('checkout/cart')->getQuote();
if (!$quote->getId()) return;
$shippingMethod = $quote->getShippingAddress()->getShippingMethod();
if ($shippingMethod) return;
$shippingAddress = $quote->getShippingAddress();
$country = 'FR'; // Some country code
$postcode = '75000'; // Some postcode
$regionId = '0'; // Some region id
$method = 'tablerate_bestway'; // Used shipping method
$shippingAddress
->setCountryId($country)
->setRegionId($regionId)
->setPostcode($postcode)
->setShippingMethod($method)
->setCollectShippingRates(true)
;
$shippingAddress->save();
$quote->save();
}
}
<sales_quote_collect_totals_before>
<observers>
<!-- Set default shipping method and rate when necessary -->
<autoshipping>
<class>My_Module_Model_Observer</class>
<method>setQuoteShippingMethod</method>
</autoshipping>
</observers>
</sales_quote_collect_totals_before>
@rickymatthews
Copy link

There's a bug in this, if you log in as a customer, add item to cart then try checkout, it throws an exception Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (mage_db.sales_flat_quote_shipping_rate``

@vahidaghazadeh
Copy link

sikim dadon aghzin gada $this hardan galib kos kesh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment