Add attribute name to configurable select option in Magento2?
-
12-01-2021 - |
Question
By default, the drop-down box for configurable products displays 'Choose an option...'. I'd like to change this to 'Select {attribute label}'.
I found the code for this in:
vendor\magento\module-configurable-product\view\frontend\templates\product\view\type\options\
Here the following code can be added to change to the required value:
<option value=""><?php /* @escapeNotVerified */ echo __('Select ').strtolower($block->escapeHtml($_attribute->getProductAttribute()->getStoreLabel())) ?></option>
When the page initially loads this seems to work, however, once the page loads this value gets instantly replaced by 'Choose an Option...' which I found loads from here:
/vendor/magento/module-configurable-product/Block/Product/View/Type/Configurable.php
Where it appears like this:
'chooseText' => __('Choose an Option...'),
Any idea how to insert the attribute name here or stop this from overwriting the change I have already made?
Solution
You also need to change that text in below file,
magento/vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js
In this file, you need to find _fillSelect method and see "chooseText" value.
element.options[0].innerHTML = this.options.spConfig.chooseText
Replace with below code
var attribute_lable = this.options.spConfig.attributes[element.id.replace(/[a-z]*/, '')]['label']; element.options[0].innerHTML = this.options.spConfig.chooseText + attribute_lable;
Note: Don't forgets to override this file and remove cache & run static-content:deploy command.
Hope this will help you.