Magento – How to get price for configurable product

configurable-productevent-observermagento-1.9price

I have configurable products like

enter image description here

I created observer and I got the price

Default price is for 1kg but customer can change the weight and flavor.

When customer changes weight and flavor price changes.

like

enter image description here

enter image description here

I created observer in that I have code like

public function saveProductMrpInOrder(Varien_Event_Observer $observer) {
        $order = $observer->getEvent()->getOrder();
        foreach($order->getAllItems() as $item) {
            $price = Mage::getModel('catalog/product')->load($item->getId())->getPrice();
            $item->setProductMrp($price);
        }
      return $this;
    }

    public function saveProductMrpInInvoice(Varien_Event_Observer $observer) {
        $invoice = $observer->getEvent()->getInvoice();
        foreach($invoice->getAllItems() as $item) {
            $price = Mage::getModel('catalog/product')->load($item->getProductId())->getPrice();
            $item->setProductMrp($price);
        }
      return $this;
    }

    public function saveProductMrpInShipment(Varien_Event_Observer $observer)
{
        $shipment = $observer->getEvent()->getShipment();
        foreach($shipment->getAllItems() as $item) {               
            $product = Mage::getModel('catalog/product')->load($item->getProductId());
            $price = $product->getPrice();
            $item->product_mrp = $price;
        }
    }

But in that I am getting default price which is for 1kg

But I want price for product according to attributes selected

How can I get that price.

Hope you understand.

Best Answer

From your question, it is not sure in which context you need to get the configurable product price.

In any context what you are missing is, you need to populate custom attribute options of the configurable product. After that, when you call getFinalPrice() on your configurable product instance you will get the correct price.

For more details, you can refer my blog post here. It shows how can populate custom attribute options of the configurable product if we have both configurable product and corresponding associated product.

For quick reference, I am adding the code snippet here.

$product        = Mage::getModel('catalog/product')->load(357); //configurable product
$optProduct     = Mage::getModel('catalog/product')->load(282); //associated simple product
$confAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$pdtOptValues   = array();
foreach ($confAttributes as $attribute) {
    $attrCode    = $attribute['attribute_code'];
    $attrId      = $attribute['attribute_id'];
    $optionValue = $optProduct->getData($attrCode);
    $pdtOptValues[$attrId] = $optionValue;
}
$product->addCustomOption('attributes', serialize($pdtOptValues));
echo $product->getFinalPrice();
Related Topic