Update product sku with customs options skus on product pages and cart
-
16-10-2019 - |
Question
How can I dynamically update the sku of a product on the product page when users select its custom options? Also, how could it then be passed into the cart page?
Example: A product with sku XXX has two custom options Y and Z, which have the options of Y1, Y2 and Z1, Z2. If a user selects Y1 and Z2, I'd like to change the sku on the page to XXX-Y1-Z2 and pass that sku to the cart.
Thanks.
Solution
If you add a custom options to a product you can add, for example for dropdown options, a product sku suffix as shown below.
On choosing an option when adding the product to cart and retrieving the SKU in the cart var_dump($_item->getSku());
you can see the products SKU has been changed
Now for dynamically updating the SKU on the product page. For this we will need to retrieve the option values SKU's which can be done in the file app/design/frontend/[package]/[template]/template/catalog/product/view/options.phtml
for example. In this case around line 190 after the javascript we add/replace some code as shown below. This will give you a javascript array which you can use when a custom option is selected to map the option ID to the SKU suffix and changing the displayed product SKU on the product page.
<dl>
<?php $options_to_sku = array();?>
<?php foreach($_options as $_option): ?>
<?php echo $this->getOptionHtml($_option) ?>
<?php
if ($_option->getType() == 'drop_down')
{
$options_to_sku["{$_option->getId()}"] = array();
foreach ($_option->getValues() as $k => $v)
{
$options_to_sku["{$_option->getId()}"]["{$v->getData('option_type_id')}"] = $v->getData('sku');
}
}
?>
<?php endforeach; ?>
</dl>
<script type="text/javascript">
var options_to_sku = <?php echo json_encode($options_to_sku);?>;
$$('.product-custom-option').each(function(elm) {
$(elm).observe('change', function() {
var sku_suffix = '';
$$('.product-custom-option').each(function(opt) {
if ($(opt).value.length==0) // no value selected
return;
var opt_id = $(opt).readAttribute('id').replace('select_','');
if (!!!options_to_sku[opt_id]) // no option values array found
return;
if (!!!options_to_sku[opt_id][$(opt).value]) // no sku found matching value id
return;
sku_suffix += '-' + options_to_sku[opt_id][$(opt).value]; // add to suffix
});
/**
* add here the code that adds the suffix to your SKU
*/
console.log(sku_suffix);
});
});
</script>
OTHER TIPS
Product page
Add the sku to the product page, add a few lines of JS, listen on change
on the <select>
and change the sku.
Cart
Implement an observer, listen to checkout_cart_product_add_after
take the product, check for the custom options and change the sku of the quote_item
. The quote_item
is saved afterwards, so no need to save it inside the controller.
$quoteItem->setSku();
Done.