3

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 */
                }

            }
        },
1
  • Please check my ans. Nov 28, 2018 at 5:49

2 Answers 2

3

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>
7
  • @Manashvi Birla i will check and getback thanks for your reply Oct 15, 2018 at 12:45
  • no @manashvi its not working Oct 15, 2018 at 13:01
  • @NagarajuKasa - can you post the structure of the select box here. may some id is mismatch Oct 15, 2018 at 13:07
  • prnt.sc/l6b1ga Oct 15, 2018 at 13:17
  • @NagarajuKasa - check the updated ans. I have changed the class Oct 15, 2018 at 13:52
1
  1. Copy and pasted configurable.js from vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js to my custom theme app/design/frontend/Vendor/Theme_Name/Magento_ConfigurableProduct/web/js/configurable.js

  2. There is a method _fillSelect: function around 356 line number as per the requirement modified as below.

      /*** Populates an option's selectable choices.
         * @private
         * @param {*} element - Element associated with a configurable option.
         */
        _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) {
             var customIndex = 0; //define custom variable here
                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++;
                        customIndex++;  //incremented                     
                    }
                    /* eslint-enable max-depth */
                }
                 //add custom code here for preselect if single option avilable
                 if(customIndex == 1){
                     setTimeout(function(){
                      $('#attribute'+attributeId).val($('#attribute'+attributeId+' option:nth-child(2)').val()).trigger('change');  
                      $("#attribute"+attributeId).prop("disabled", false);
                     },200);                
                }               
            }
        },
    
  3. Executed deploy commands and cleared flush cache

4
  • I have to use this code but if in drodpdown attribute with swatch image not set so how to set in first option with image
    – Rv Singh
    Jan 17, 2019 at 9:12
  • Please go to my question "magento.stackexchange.com/questions/257577/…"
    – Rv Singh
    Jan 17, 2019 at 9:14
  • @RvSingh actually above code is worked for if drop down has a single option, it will select automatically based on selection. may be my solutions won't solve u r problem.. Jan 18, 2019 at 4:28
  • Thanks for reply but in detail page i have two option for configurable product there i need to remove "Choose an Option" in drop down menu and have the first attribute value be the top choice
    – Rv Singh
    Jan 18, 2019 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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