I have this script to show the dynamic sku on select option, but i cannot get working.
Is loading the correct sku, but on select nothing happen.
This code ge
The script is almost correct except for $simple_product->getSelectLabel()
being a wrong key. No such method/property exists in a simple product model. In order to make the script work, this key should be replaced with a right one - a Product Id. Utilizing product id, it is possible to find the sku of the product being selected.
So, first of all you need to reorganize itemId
array to make it a "productId => productSku" map:
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getSku();
}
Then you need to change the "onchange" function call to pass Configurable's attribute id to the changeSku()
function. Thus the underlying logic is able to search appropriate simple product's attributes.
onchange="return changeSku(getAttributeId() ?>, this);">
And after that you need utilize configurable's config in order to map selected simple product's attribute id to the product id selected:
function changeSku(confAttributeId, sel) {
var productMap = jsonEncode($productMap);?>;
var selectedAttributeId = sel.options[sel.selectedIndex].value;
if (selectedAttributeId) {
var options = spConfig.config.attributes[confAttributeId].options;
var productId = options.find(function (option) {return option.id == selectedAttributeId}).products[0]
$("sku-container").update("Product Id: " + productMap[productId]);
} else {
$("sku-container").update("Product Id: Select an option to display Product Id");
}
}
For your reference, below is the summary of how the whole template looks like (I've beautified it a little):
getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
isSaleable() && count($_attributes)):?>
- decoratedIsLast){?> class="last">
setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
$productMap = array();
foreach($col as $simpleProduct){
$productMap[$simpleProduct->getId()] = $simpleProduct->getSku();
}
?>
This will do the task you originally needed.
Also note the following
foreach
-iterations. All the methods like $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions()
are better to be moved to block. This reduces code complexity.
Hope it helps.