10

I am trying to create a product with two custom text fields: Length and Width. When the user types in both a length and width, the price needs to calculate via custom formula.

I'm trying to find the correct event to connect an observer to - anybody know what that might be?

Here's what I know and have tried

1) the custom field text box in the product view has an onchange event that I haven't figured out how to tap into yet via an observer event - "opConfig.reloadPrice()

2) If I build an observer on the event sales_quote_add_item, then I can change the price via formula when it's added to the cart. With this method I still need a way to change it in the product view before it's added to cart.

3) I've also tried the event catalog_product_get_final_price but this seem to only fire when the product page is loaded, so after a product length or width is added, it doesn't re-fire.

Any ideas would be greatly appreciated!

1
  • did Fabian's this help you? If so could you please accept or clarify so we could help?
    – philwinkle
    Commented Nov 7, 2014 at 17:35

2 Answers 2

2

I used for this usecase sales_quote_collect_totals_before:

/**
 * Set prices
 *
 * @param Varien_Event_Observer $observer
 */
public function salesQuoteCollectTotalsBefore(Varien_Event_Observer $observer)
{
    /* @var $quote Mage_Sales_Model_Quote */
    $quote = $observer->getQuote();
    foreach ($quote->getAllItems() as $quoteItem) {
        if (is your product of choice) {
            /* @var $quoteItem Mage_Sales_Model_Quote_Item */
            $product = $quoteItem->getProduct();
            $price = whatever formula you want to use;
            $product->setPrice($price);
        }
    }
}

On the client side, you can just use a few lines of JS to update the price?

2

catalog_product_get_final_price is the correct server side event, it's not only fired when the product page is loaded but also when the product gets added to the cart. In this case you have all the selected custom options available with:

$observer->getProduct()->getCustomOption($customOptionName);

(See also: Is there any way where user can set the custom desired price greater than zero and proceed to cart for any product?)


Recalculating the price while on the product page is another topic and needs JavaScript. reloadPrice is the right function to hook into, I would extend it like this:

Product.prototype.reloadPrice = Product.prototype.reloadPrice.wrap(function(callOriginal) {
    if (should_be_calculated_based_on_length_and_with) {

        // copy the original reloadPrice function here and change how `price` is calculated

    } else {
        callOriginal();
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.