Magento – How to display the sku of product in javascript

cejavascriptmagento-1.9sku

When the below line is used in JavaScript it displays the Product Id:

var productId = optionsPrice.productId;
window.alert(productId);

Similarly how to get & display sku of the configurable product & simple product?

Best Answer

You need to overwrite Mage_Catalog_Block_Product_View_Type_Configurable class


#app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php

public function getJsonConfig()
{
    $config = Zend_Json::decode(parent::getJsonConfig());

    $productsCollection = $this->getAllowProducts();
    foreach ($productsCollection as $product) {
        $productId = $product->getId();
        $config['products_sku'][$productId]['sku'] = $product->getSku();
    }
    $jsonConfig = Zend_Json::encode($config);
    return $jsonConfig;
}

[Updated]


#app/etc/modules/SR_Stackexchange.xml
<?xml version="1.0"?>
<config>
    <modules>
        <SR_Stackexchange>
            <active>true</active>
            <codePool>local</codePool>
        </SR_Stackexchange>
    </modules>
</config>

Create app/code/local/SR/Stackexchange/etc/config.xml


<?xml version="1.0"?>

<config>
    <modules>
        <SR_Stackexchange>
            <version>0.0.0.1</version>
        </SR_Stackexchange>
    </modules>
    <global>
        <blocks>
            <stackexchange>
                <class>SR_Stackexchange_Block</class>
            </stackexchange>
            <catalog>
                <rewrite>
                    <product_view_type_configurable>SR_Stackexchange_Block_Product_View_Type_Configurable</product_view_type_configurable>
                </rewrite>
            </catalog>
        </blocks>
     </global>
</config>


Create app/code/local/SR/Stackexchange/Block/Product/View/Type/Configurable.php


class SR_Stackexchange_Block_Product_View_Type_Configurable extends Mage_Catalog_Block_Product_View_Type_Configurable
{
    public function getJsonConfig()
    {
        $config = Zend_Json::decode(parent::getJsonConfig());
        $currentProduct = $this->getProduct();
        $config['sku'] = $currentProduct->getSku();
        $productsCollection = $this->getAllowProducts();
        foreach ($productsCollection as $product) {
            $productId = $product->getId();
            $config['products_sku'][$productId]['sku'] = $product->getSku();
        }

        $jsonConfig = Zend_Json::encode($config);
        return $jsonConfig;
    }
}

Clear cache.

[Updated]

Suppose you have all config in var config. So you can display sku following way:


// For parent sku
console.log(config['sku'])

//You get all child sku
console.log(config['products_sku']);

//Specific child sku by product_id
var product_id = 294;
console.log(config['products_sku'][product_id]['sku'])

Related Topic