Do you want to display first options of configurable product to be selected?
Step 1: Create the module
Create theΒ registration.phpΒ Β file inΒ app/code/Thecoachsmb
/Productmodule
/ for theΒ module
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Thecoachsmb_Productmodule',
__DIR__
);
Create directoryΒ app/code/Thecoachsmb
/Productmodule
/etc
Put this file in it :Β module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Thecoachsmb_Productmodule" setup_version="1.0.0">
<sequence>
<module name="Magento_ConfigurableProduct"/>
<module name="Magento_Swatches"/>
</sequence>
</module>
</config>
Step 2: Show First Option Selected of configurable product
To implement this, we will need to modify swatch-renderer.js
Β file located inΒ Magento_Swatches/view/base/web/js/swatch-renderer.js
But in the core file we can not add the code. SoΒ To modify the js file, we need toΒ override js file in our module
Letβs override the js file now,
CreateΒ requirejs-config.js file in app/code/Thecoachsmb
/Productmodule
/view/frontend/
with the content as below:
var config = { map: { '*': { 'Magento_Swatches/js/swatch-renderer':'Thecoachsmb_Productmodule/js/swatch-renderer' } } };
CreateΒ swatch-renderer.jsΒ file in directory :Β app/code/Thecoachsmb
/Productmodule
/view/frontend/web/js/
Copy the code fromΒ vendor/magento/module_swatches/view/base/web/js/swatch-renderer.jsΒ to our moduleΒ Β swatch-renderer.js.
In the function _RenderControls: function () {
add below lines at the last of this function:-
var swatchLength = $('.swatch-attribute').length; if(swatchLength >= 1){ if($('.swatch-attribute').hasClass("size")){ $('.swatch-option').first().trigger('click'); } } $('.swatch-option.color').first().click();
as shown below:
Then, remove folder present inside pub/static/frontend/ and var/view_preprocessed
Then Run below commads:
php bin/magento se:s:d -f && php bin/magento c:f
That’s it.