Magento – Magento 2 configurable product variation dropdown attribute/s want to select automatically, if it has single option

attributesconfigurable-productdrop-downsmagento2

We have configurable product have some drop down attribute variations. here would like to choose by default when the attribute has single option in the product view page.

Can you please give me some suggestions?

automatic selection

I found template file in the vendor:-

vendor/magento/module-configurable-product/view/frontend/templates/product/view/type/options/configurable.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>

<?php
/** @var $block \Magento\ConfigurableProduct\Block\Product\View\Type\Configurable*/
$_product    = $block->getProduct();
$_attributes = $block->decorateArray($block->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <?php foreach ($_attributes as $_attribute): ?>
        <div class="field configurable required">
            <label class="label" for="attribute<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>">
                <span><?= $block->escapeHtml($_attribute->getProductAttribute()->getStoreLabel()) ?></span>
            </label>
            <div class="control">
                <select name="super_attribute[<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>]"
                        data-selector="super_attribute[<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>]"
                        data-validate="{required:true}"
                        id="attribute<?= /* @escapeNotVerified */ $_attribute->getAttributeId() ?>"
                        class="super-attribute-select">
                    <option value=""><?= /* @escapeNotVerified */ __('Choose an Option1...') ?></option>
                </select>
            </div>
        </div>
    <?php endforeach; ?>
    <script type="text/x-magento-init">
        {
            "#product_addtocart_form": {
                "configurable": {
                    "spConfig": <?= /* @escapeNotVerified */ $block->getJsonConfig() ?>,
                    "gallerySwitchStrategy": "<?php /* @escapeNotVerified */ echo $block->getVar('gallery_switch_strategy',
                        'Magento_ConfigurableProduct') ?: 'replace'; ?>"
                }
            }
        }
    </script>
<?php endif;?>

pub/static/frontend/Magento/luma/en_US/Magento_ConfigurableProduct/js/configurable.js

_fillSelect: function (element) {
            var attributeId = element.id.replace(/[a-z]*/, ''),
                options = this._getAttributeOptions(attributeId),
                prevConfig,
                index = 1,
                allowedProducts,
                i,
                j;

            this._clearSelect(element);
            element.options[0] = new Option('', '');
            element.options[0].innerHTML = this.options.spConfig.chooseText;
            prevConfig = false;

            if (element.prevSetting) {
                prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
            }

            if (options) {
                for (i = 0; i < options.length; i++) {
                    allowedProducts = [];

                    /* eslint-disable max-depth */
                    if (prevConfig) {
                        for (j = 0; j < options[i].products.length; j++) {
                            // prevConfig.config can be undefined
                            if (prevConfig.config &&
                                prevConfig.config.allowedProducts &&
                                prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                                allowedProducts.push(options[i].products[j]);
                            }
                        }
                    } else {
                        allowedProducts = options[i].products.slice(0);
                    }

                    if (allowedProducts.length > 0) {
                        options[i].allowedProducts = allowedProducts;
                        element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);

                        if (typeof options[i].price !== 'undefined') {
                            element.options[index].setAttribute('price', options[i].prices);
                        }

                        element.options[index].config = options[i];
                        index++;
                    }

                    /* eslint-enable max-depth */
                }

            }
        },

Best Answer

You can use custom jquery to select first option automatically, when there is a single option, like below in phtml file :

<script>
require(['jquery', 'jquery/ui'], function($){ 
    if(jQuery('.super-attribute-select option').length == 1){
        jQuery('.super-attribute-select option:first').attr('selected','selected');
    }
});
</script>
Related Topic