The idea was here to extend the class \Magento\Swatches\Block\Product\Renderer\Listing\Configurable
and particularly the method _getAdditionalConfig()
. Below is my code, the 2 images roles I wanted to extract are called category_mobile
and category_tablet
.
app/code/Memes/Extendjsonconfig/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Memes_Extendjsonconfig',
__DIR__
);
app/code/Memes/Extendjsonconfig/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" type="Memes\Extendjsonconfig\Block\Product\Renderer\Listing\Configurable" />
</config>
app/code/Memes/Extendjsonconfig/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Memes_Extendjsonconfig" setup_version="0.0.1"/>
</config>
app/code/Memes/Extendjsonconfig/Block/Product/Renderer/Listing/configurable.php
<?php
/**
* Created by memes (http://chezmemes.com)
* Date: 26/10/2016
* Time: 6:02 PM
*/
namespace Memes\Extendjsonconfig\Block\Product\Renderer\Listing;
class Configurable extends \Magento\Swatches\Block\Product\Renderer\Listing\Configurable
{
protected function _getAdditionalConfig()
{
$image_mobile = 'category_mobile';
$image_tablet = 'category_tablet';
return [$image_mobile => $this->getOptionImages($image_mobile), $image_tablet => $this->getOptionImages($image_tablet) ];
}
protected function getOptionImages($imageRole)
{
$images = [];
foreach ($this->getAllowProducts() as $product) {
$mobileImage = $product->getData($imageRole);
if(isset($mobileImage) && $mobileImage != 'no_selection' ){
$mobileImageAttr = $product->getCustomAttribute( $imageRole );
$image = $mobileImageAttr->getValue();
}
else{
$image="";
}
$images[$product->getId()] =
[
'path' => $image
];
}
return $images;
}
}
This gives me the relative path of the images in the folder http://www.store.com/pub/media/catalog/product
, I can then use it in my Javascript to update whatever I want.
This would be easily extendable to any other attribute needed.
A variant would be to use a Plugin rather than a preference, this is discussed in this question