The configurable product based on variation product images are changing, but not SKU, is there any way to change SKU also?
2 Answers
You have to override function getAllSizeImages()
from Magento\Swatches\Helper\Data.php
file.
protected function getAllSizeImages(Product $product, $imageFile)
{
return [
'large' => $this->imageHelper->init($product, 'product_page_image_large')
->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)
->setImageFile($imageFile)
->getUrl(),
'medium' => $this->imageHelper->init($product, 'product_page_image_medium')
->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)
->setImageFile($imageFile)
->getUrl(),
'small' => $this->imageHelper->init($product, 'product_page_image_small')
->setImageFile($imageFile)
->getUrl(),
'sku' => $product->getSku()
];
}
After change variant of product you have got response with sku of variant and you can change sku based on response using js.
Out of the box, when choosing options, the images and the price will change. But not SKU.
More information about which elements on the page change when options are selected can be found here: Magento\ConfigurableProduct\Block\Product\View\Type\Configurable::getJsonConfig()
.
In order to display the SKU of the selected product, you can create a Plugin (Interceptor) for Magento\ConfigurableProduct\Block\Product\View\Type\Configurable::getJsonConfig()
where you need to add missing SKU
for each simple product.
Switching SKU
when selecting an option can be implemented in vendor/magento/module-swatches/view/base/web/js/swatch-renderer.js
and vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js
depending on the type of attribute.
I made free VCT Change SKU Dynamically
module that solve this problem.