Magento – Set Shipping Method in Cart

cartmagento-1.9shipping-methods

I'm trying to set a custom shipping method in the cart by ajax. Using magento 1.9.0.1

It's sending an ajax-call to a new controller to set the new shipping method and returns the result and the updated cart totals.

Thats working but after an pagerefresh it's again showing the default shipping method. I have tested it with another shipping method that should work but it's the same, always back to default after an refresh.

I tried already all kind of ways to set the method. And It's updating the entries in the db 'sales_flat_quote_address' to the new shipping method. Basicly it's working…

I haven't found any observer or other call thats overriding the shipping method. It's changing back while loading the base grand totals in the quote.

    $cart = Mage::getSingleton('checkout/cart');
    $quote = $cart->getQuote();

    $shippingAddress = $quote->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)
        ->collectShippingRates()
        ->setShippingMethod($method);

    $quote->setTotalsCollectedFlag(false)->collectTotals()->save();

or

    $result = $this->getOnepage()->saveShippingMethod($method);
    $this->getOnepage()->getQuote()->collectTotals()->save();

and similar ways.

Best Answer

Did you try to set a default country before saving the shipping method? It worked for me (Mage 1.7).

$quote = $session->getQuote();
/* 
 * ...your default method affectation logic
 */
$country = "FR"; /* To test */
$address = $quote->getShippingAddress();
$address->setCountryId($country)->setCollectShippingRates(true)->collectShippingRates();
$quote->setShippingMethod($code)->save();

That makes worked for my case.

Related Topic