Update Product SKU with Custom Options SKUs in Magento

ajaxcustom-optionsproduct-attributesimple-productsku

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.

Best Answer

If you add a custom options to a product you can add, for example for dropdown options, a product sku suffix as shown below.

enter image description here

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

enter image description here

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>