3

I'm trying to have swatch option value of color auto-selected for Products that only have one color.

If a user selects some product from the category page, the product page is displayed with attributes like Color, Shape, and Size. Some of the products only have one color though, but still require the user to click-select it. I want the color to be automatically selected for all single-colored products when the pages load.

1

This is an old question, but I ran into the same issue today. I solved it using jquery. I added this to the view.phtml template and it looks to work for me. Just posting it here in case someone else has a similar problem.

$j('.configurable-swatch-list').each(function() {
    if ($j(this).find('li').length == 1) {
        $j(this).find('li:first-child a span').trigger("click");
    }
});

This will target all configurable swatch lists, you can change the code to just look for the particular swatch list you care about.

0

Can you please tell me which Magento version you are using? And also share the path of above question., What is the path of view.phtml file which u are modifying. Sorry due to new i am not able to reply to your comment.

$j('.configurable-swatch-list').each(function() {
if ($j(this).find('li').length == 1) {
    $j(this).find('li:first-child a span').trigger("click");
}

});

0

Update _init() function of file app/design/frontend/Vendor/Theme/Magento_Swatches/web/js/swatch-renderer.js as given below:

_init: function () {
    if (_.isEmpty(this.options.jsonConfig.images)) {
        this.options.useAjax = true;
        // creates debounced variant of _LoadProductMedia()
        // to use it in events handlers instead of _LoadProductMedia()
        this._debouncedLoadProductMedia = _.debounce(this._LoadProductMedia.bind(this), 500);
    }

    if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
        // store unsorted attributes
        this.options.jsonConfig.mappedAttributes = _.clone(this.options.jsonConfig.attributes);
        this._sortAttributes();
        this._RenderControls();
        this._setPreSelectedGallery();
        $(this.element).trigger('swatch.initialized');

        /* your modification here */
        $('.page-product-configurable .swatch-attribute .swatch-attribute-options div.swatch-option').first().click();
        /* your modification ended */

    } else {
        console.log('SwatchRenderer: No input data received');
    }
    this.options.tierPriceTemplate = $(this.options.tierPriceTemplateSelector).html();
},

Note: I have tested this code with Magento 2.2.5 version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.