cancel
Showing results for 
Search instead for 
Did you mean: 

Auto select color swatches cache issue in listing page

SOLVED

Auto select color swatches cache issue in listing page

Recently I customized category listing page to auto-select the color swatch, when a color swatch is selected in the layered navigation.

 

Everything is working fine with cache disabled. If the cache is enabled, even though the filters are cleared, the previously selected swatches remain selected.

I know this is because the template is getting cached. I tried using "cacheable=false" but no help. Can anyone please help me to resolve this, I just want a block not to be cached or any other better way.

 

The "colorOptionId" is getting cached and not getting refreshed with clear filters. 

 

image.png

 

--------
Give Kudos if it helped or if the problem is solved Accept it as a solution

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Auto select color swatches cache issue in listing page

Hi @Mayur Bhuva,

yes, it is a default functionality but the problem is the color attribute used for layered navigation is different from the one used in listing page. So, I tried to map them both. Anyway, I found the way to do. Here it is.

As the logic I previously used is within the template, cache caused the problem. Now I injected the additional parameter into "jsonSwatchConfig" array and tried to use it within swatch-renderer.js.

 

In order to add a parameter in jsonSwatchConfig, you have to override \Magento\Swatches\Block\Product\Renderer\Listing\Configurable.php

To add that parameter within in the "div" override "swatch-renderer.js" and add that parameter within this function(_RenderSwatchOptions). Here is the code sample demonstrating the same with a parameter called "customparam".

_RenderSwatchOptions: function (config, controlId) {
        var optionConfig = this.options.jsonSwatchConfig[config.id],
            optionClass = this.options.classes.optionClass,
            moreLimit = parseInt(this.options.numberToShow, 10),
            moreClass = this.options.classes.moreButton,
            moreText = this.options.moreButtonText,
            countAttributes = 0,
            html = '';

        if (!this.options.jsonSwatchConfig.hasOwnProperty(config.id)) {
            return '';
        }

        $.each(config.options, function () {
            var id,
                type,
                value,
                thumb,
                label,
                colorOptionId,
                attr;

            if (!optionConfig.hasOwnProperty(this.id)) {
                return '';
            }

            // Add more button
            if (moreLimit === countAttributes++) {
                html += '<a href="#" class="' + moreClass + '">' + moreText + '</a>';
            }

            id = this.id;
            type = parseInt(optionConfig[id].type, 10);
            value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : '';
            thumb = optionConfig[id].hasOwnProperty('thumb') ? optionConfig[id].thumb : '';
            customparam = optionConfig[id].hasOwnProperty('customparam ') ? optionConfig[id].customparam : '';
            label = this.label ? this.label : '';
            attr =
                ' id="' + controlId + '-item-' + id + '"' +
                ' custom-id="' + customparam + '"'+
                ' aria-checked="false"' +
                ' aria-describedby="' + controlId + '"' +
                ' tabindex="0"' +
                ' option-type="' + type + '"' +
                ' option-id="' + id + '"' +
                ' option-label="' + label + '"' +
                ' aria-label="' + label + '"' +
                ' option-tooltip-thumb="' + thumb + '"' +
                ' option-tooltip-value="' + value + '"' +
                ' role="option"';

            if (!this.hasOwnProperty('products') || this.products.length <= 0) {
                attr += ' option-empty="true"';
            }

            if (type === 0) {
                // Text
                html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) +
                    '</div>';
            } else if (type === 1) {
                // Color
                html += '<div class="' + optionClass + ' color" ' + attr +
                    ' style="background: ' + value +
                    ' no-repeat center; background-size: initial;">' + '' +
                    '</div>';
            } else if (type === 2) {
                // Image
                html += '<div class="' + optionClass + ' image" ' + attr +
                    ' style="background: url(' + value + ') no-repeat center; background-size: initial;">' + '' +
                    '</div>';
            } else if (type === 3) {
                // Clear
                html += '<div class="' + optionClass + '" ' + attr + '></div>';
            } else {
                // Default
                html += '<div class="' + optionClass + '" ' + attr + '>' + label + '</div>';
            }
        });

        return html;
    }


--------
Give Kudos if it helped or if problem is solved Accept it as a solution

View solution in original post

4 REPLIES 4

Re: Auto select color swatches cache issue in listing page

@kalyanchakri

 

You can auto select the color swatches using another way also.

 

Navigate to app/design/frontend/Vendor/theme/Magento_Swatches/web/js/swatch-renderer.js

 

 

Make changes in the _init() function as shown below.

 

_init: function () {  
        if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
            this._sortAttributes(); 
            this._RenderControls();  

            //try following condition to select the first attribute value
            if(this.options.jsonConfig.attributes.length == 1){                $('.swatch-attribute .swatch-attribute-options div.swatch-option').first().click();
            }

        } else {            console.log('SwatchRenderer: No input data received');
        }
    },

 

 

If you find my answer useful, Please click Kudos & Accept as Solution.

Re: Auto select color swatches cache issue in listing page

Hi @Mayur Bhuva,

Thanks for your reply. I came across this while doing customization. But my goal is not to select the first swatch. My goal is to select the related swatch.

Let's say I am selecting pink swatch in the filter then the pink swatches should get selected in the listing page irrespective of the order. Likewise for other color swatches.

--------
Give Kudos if it helped or if the problem is solved Accept it as a solution

Re: Auto select color swatches cache issue in listing page

@kalyanchakri

 

That is a default feature of Magento 2. 

When you select any color from left layered navigation filters, it will automatically select the swatches.

 

If it's not working in your case, you can add a jquery to trigger click on your desired color option id.

 

An example is given below.

 

jQuery('ol.product-items li.product-item').each(function(){
	jQuery(this).find('.swatch-attribute .swatch-option.color').each(function(){
		if(jQuery(this).attr('option-id') == '57'){
			jQuery(this).click();
		}
	});
});
If you find my answer useful, Please click Kudos & Accept as Solution.

Re: Auto select color swatches cache issue in listing page

Hi @Mayur Bhuva,

yes, it is a default functionality but the problem is the color attribute used for layered navigation is different from the one used in listing page. So, I tried to map them both. Anyway, I found the way to do. Here it is.

As the logic I previously used is within the template, cache caused the problem. Now I injected the additional parameter into "jsonSwatchConfig" array and tried to use it within swatch-renderer.js.

 

In order to add a parameter in jsonSwatchConfig, you have to override \Magento\Swatches\Block\Product\Renderer\Listing\Configurable.php

To add that parameter within in the "div" override "swatch-renderer.js" and add that parameter within this function(_RenderSwatchOptions). Here is the code sample demonstrating the same with a parameter called "customparam".

_RenderSwatchOptions: function (config, controlId) {
        var optionConfig = this.options.jsonSwatchConfig[config.id],
            optionClass = this.options.classes.optionClass,
            moreLimit = parseInt(this.options.numberToShow, 10),
            moreClass = this.options.classes.moreButton,
            moreText = this.options.moreButtonText,
            countAttributes = 0,
            html = '';

        if (!this.options.jsonSwatchConfig.hasOwnProperty(config.id)) {
            return '';
        }

        $.each(config.options, function () {
            var id,
                type,
                value,
                thumb,
                label,
                colorOptionId,
                attr;

            if (!optionConfig.hasOwnProperty(this.id)) {
                return '';
            }

            // Add more button
            if (moreLimit === countAttributes++) {
                html += '<a href="#" class="' + moreClass + '">' + moreText + '</a>';
            }

            id = this.id;
            type = parseInt(optionConfig[id].type, 10);
            value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : '';
            thumb = optionConfig[id].hasOwnProperty('thumb') ? optionConfig[id].thumb : '';
            customparam = optionConfig[id].hasOwnProperty('customparam ') ? optionConfig[id].customparam : '';
            label = this.label ? this.label : '';
            attr =
                ' id="' + controlId + '-item-' + id + '"' +
                ' custom-id="' + customparam + '"'+
                ' aria-checked="false"' +
                ' aria-describedby="' + controlId + '"' +
                ' tabindex="0"' +
                ' option-type="' + type + '"' +
                ' option-id="' + id + '"' +
                ' option-label="' + label + '"' +
                ' aria-label="' + label + '"' +
                ' option-tooltip-thumb="' + thumb + '"' +
                ' option-tooltip-value="' + value + '"' +
                ' role="option"';

            if (!this.hasOwnProperty('products') || this.products.length <= 0) {
                attr += ' option-empty="true"';
            }

            if (type === 0) {
                // Text
                html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) +
                    '</div>';
            } else if (type === 1) {
                // Color
                html += '<div class="' + optionClass + ' color" ' + attr +
                    ' style="background: ' + value +
                    ' no-repeat center; background-size: initial;">' + '' +
                    '</div>';
            } else if (type === 2) {
                // Image
                html += '<div class="' + optionClass + ' image" ' + attr +
                    ' style="background: url(' + value + ') no-repeat center; background-size: initial;">' + '' +
                    '</div>';
            } else if (type === 3) {
                // Clear
                html += '<div class="' + optionClass + '" ' + attr + '></div>';
            } else {
                // Default
                html += '<div class="' + optionClass + '" ' + attr + '>' + label + '</div>';
            }
        });

        return html;
    }


--------
Give Kudos if it helped or if problem is solved Accept it as a solution