Magento – How to get products attributes and use them as condition to set shipping price

attributescustommethodspriceshipping

Below is my setShippingCost function in my Observer.php:

public function setShippingCost($evt){
    $session = Mage::getSingleton('checkout/session');

    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $quoteid = $quote->getId();

    $shipping_code = $quote->getShippingAddress()->getShippingMethod();
    $request = $evt->getRequest();        

    $new_shipping_rate = $request->getParam('this_shipping_rate_'.$shipping_code, false);

    if($quoteid) {
        try{
            $address = $quote->getShippingAddress();
            if($address->getAddressType()=='shipping'){

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

                foreach ($rates as $carrier) {
                    foreach ($carrier as $rate) {
                        $rate->setPrice($new_shipping_rate);
                        $rate->save();
                    }//endforeach
                }//endforeach
                $this->collectTotals($quote, $shipping_code, $new_shipping_rate);
            }//endif

            $quote->collectTotals();

        } catch (Exception $e) {            
            Mage::logException($e);
            $response['error'] = $e->getMessage();
        }//endtrycatch
    }//endif

}//endfct

There conditions that need to be considered before setting the shipping cost. These are (custom attributes) length, thickness, and breadth and (default) weight.

How do I get each of the products attributes (mentioned above)? Or can this be done inside this function?

Sorry as I'm quite new to Magento.

Thank you!!

Best Answer

The $quote object holds the items that are currently in the cart. But whats important here is that to get hold of custom attributes you need to add these to your config.xml file. Otherwise it is possible to get hold of but you have to jump thro a lot of hoops.

So add this to config.xml

<sales>
    <quote>
        <item>
            <product_attributes>
                <length />
                <width />
                <height />
            </product_attributes>
        </item>
    </quote>
</sales>

Then when you make the call $item->getProduct() it will get these fields.

The way you are coding this is incorrect though, whenever you have a new carrier you should be coding as such, not using observers to add rates into the system. Because the shipping rate calculation is called from many places, its just not the correct approach. Create a custom shipping extension, then do in there = see http://inchoo.net/magento/custom-shipping-method-in-magento/ , there are lots of tutorials on this.

Related Topic