I am displaying custom options for my products on the product list. The problem is that when you select an option, the price is not updated. This works fine on the individual product page, but not on the product list.
Here's the code I'm using to display the custom options:
Please don't use this code in production. It is messy and incomplete.
<?php $productSku = $_product->getSku();
$product = Mage::getModel('catalog/product');
$productId = $product->getIdBySku( $productSku );
$product = Mage::getModel("catalog/product")->load($productId);
$attVal = $product->getOptions();
$optStr = "";
// loop through the options
foreach($attVal as $optionKey => $optionVal) {
//$optStr .= "<br/>";
//$optStr .= $optionVal->getTitle().": ";
$optStr .= "<select style='display:block; clear:both;' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal) {
$optStr .= "<option value='".$valuesVal->getId()."'>".$valuesVal->getTitle()."</option>";
}
$optStr .= "</select>";
}
echo($optStr );
?>
Any ideas on how I can trigger the price change? Thanks.
Best Answer
First, before I get to your question, reloading a model like you are doing is very bad style.
$_product
contains the product data, loaded as part of the product collection$_product->getId()
would have given you the same.Lets assume you have 20 products in the collection, this results in at least 60 additional queries being executed. I'm sorry, but I want to point that out so your code isn't used as a bad example by others.
Now, to get to your actual question: Updating the display of the product price is handled by the JavaScript in js/varien/product.js. To start with, this file isn't included in the product list pages by default. You need to add the following layout XML to change that:
The next problem you encounter is that the script assumes there is only a single product on the page. In the single product page template, catalog/product/view.phtml, you can see:
This global JavaScript Variable,
optionsPrice
, is also referred to in the product.js script, in the Product.Config.reloadPrice() method:So you will need to
In addition to the JavaScript in the product.js file, you also need to customize the template catalog/product/view/options.phtml.
Again, that script assumes there is only a single products options per page:
You will need to turn that into an array, indexed by product ID, as well. Also, the global
optionsPrice
variable is referred to by the code a couple of times. Make sure that they always access the object by the correct product ID.To summarize:
Mage_Catalog_Block_Product_View_Options
block for each of the products to render the options instead of building the HTML yourselfQuite a bit of work, but doable. I'm pretty sure there also are a number of extensions that would do what you want.