golaod
golaod

Reputation: 65

Change price for shipping methods on the fly

I know there are bunch of answers and question with similar problem, but I will inform at the beginning. I am not asking about my own shipping method, but about all available methods.

I found a code which I used to do it, weird thing is: it was working a while - don't know what I changed that it stopped.

class Oversizeshipping_Model_Observer
    extends Varien_Event_Observer
{
    public function appendPriceToShipping($observer)
    {
        $address = $observer->getQuoteAddress();
        #Mage::log($address->getAddressType(), Zend_Log::DEBUG, 'event.log', true);
        if($address->getAddressType() === $address::TYPE_SHIPPING){
            $price = 0;
            $resource = Mage::getResourceModel('catalog/product');
            foreach($address->getAllItems() as $item) {
                try {
                    $oversizePrice = $resource->getAttributeRawValue($item->getProduct()->getId(), 'oversize_shipping_price', $item->getStoreId());
                } catch( Exception $e ) {
                    $oversizePrice = 0;
                }
                if($oversizePrice > 0) {
                    $price += $oversizePrice;
                }
            }

            $address->setShippingAmount($price);
            $address->setBaseShippingAmount($price);

            $rates = $address->collectShippingRates()
                     ->getGroupedAllShippingRates();
            foreach ($rates as $carrier) {
                foreach ($carrier as $rate) {
                    $rate->setPrice((float)$rate->getPrice()+$price);
                    $rate->save();
                }
            }
            $address->save();
        }
    }
}

That observer method is fired on sales_quote_address_collect_totals_after. As I mentioned before, it worked ( was adding price even to free shipping methods ), but it stopped.

Can someone point me a typo, missed method call or smth ?

Upvotes: 2

Views: 4892

Answers (2)

Anton Suslov
Anton Suslov

Reputation: 103

Your approach gonna fail if you configure Shipping Taxes.

Try to override Mage_Shipping_Model_Rate_Result::append method instead.

Upvotes: 1

golaod
golaod

Reputation: 65

First of all I deleted code:

$address->setShippingAmount($price);
$address->setBaseShippingAmount($price);

That was forcing additional price to be visible in summary as the total shipping price, instead additional price+shipping method price.

Also added:

$address->setCollectShippingRates(false);

just before:

$rates = $address->collectShippingRates()
                 ->getGroupedAllShippingRates();

and that fixed my issue with not updated rate prices.

Extra:

Same observer can be used to disable some rates. Just use:

$rate->isDeleted(true);

Upvotes: 0

Related Questions