Hello Magento Friends,
Today I am going to explain How to Show Out of Stock Options for Configurable Products Dropdown in Magento 2.
For configurable products, if any option is out of stock, it does not display on the product page. For example, if you sell tshirt with sizes S, M, L, and XL and from them L is sold out, it is not displayed to customers. Only S, M, and XL are displayed. Instead of that, you can display out of stock products in the dropdown with grey color so that customers are aware of your offerings.
You can even notify customers when the product is back in stock with the help of Magento 2 Out of Stock Notification Extension. The Magento 2 store owners can manage out of stock products list and add more quantity.
For now, let’s look at the steps to Show Out of Stock Options for Configurable Products Dropdown in Magento 2.
Contents
Steps to Show Out of Stock Options for Configurable Products Dropdown in Magento 2:
Step 1: First, we need to create a “di.xml” file inside the etc directory of our extension
app\code\Vendor\Extension\etc
Now, add the below code
1 2 3 4 5 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\Swatches\Block\Product\Renderer\Configurable" type="Vendor\Extension\Block\Product\View\Type\Configurable"/> </config> |
Step 2: Then, we need to create a “Configurable.php” file inside the extension at the following path.
app\code\Vendor\Extension\Block\Product\View\Type
And add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
<?php namespace Vendor\Extension\Block\Product\View\Type; use Magento\Catalog\Block\Product\Context; use Magento\Catalog\Helper\Product as CatalogProduct; use Magento\ConfigurableProduct\Helper\Data; use Magento\ConfigurableProduct\Model\ConfigurableAttributeData; use Magento\Customer\Helper\Session\CurrentCustomer; use Magento\Framework\Json\EncoderInterface; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Catalog\Model\Product; use Magento\Framework\Stdlib\ArrayUtils; use Magento\Store\Model\ScopeInterface; use Magento\Swatches\Helper\Data as SwatchData; use Magento\Swatches\Helper\Media; use Magento\Swatches\Model\Swatch; class Configurable extends \Magento\Swatches\Block\Product\Renderer\Configurable { public function __construct( Context $context, ArrayUtils $arrayUtils, EncoderInterface $jsonEncoder, Data $helper, CatalogProduct $catalogProduct, CurrentCustomer $currentCustomer, PriceCurrencyInterface $priceCurrency, ConfigurableAttributeData $configurableAttributeData, SwatchData $swatchHelper, Media $swatchMediaHelper, array $data = [] ){ $this->swatchHelper = $swatchHelper; $this->swatchMediaHelper = $swatchMediaHelper; parent::__construct( $context, $arrayUtils, $jsonEncoder, $helper, $catalogProduct, $currentCustomer, $priceCurrency, $configurableAttributeData, $swatchHelper, $swatchMediaHelper, $data ); } public function getJsonConfig() { $store = $this->getCurrentStore(); $currentProduct = $this->getProduct(); $regularPrice = $currentProduct->getPriceInfo()->getPrice('regular_price'); $finalPrice = $currentProduct->getPriceInfo()->getPrice('final_price'); $options = $this->getOptions($currentProduct, $this->getAllowProducts()); $attributesData = $this->configurableAttributeData->getAttributesData($currentProduct, $options); $config = [ 'attributes' => $attributesData['attributes'], 'template' => str_replace('%s', '<%- data.price %>', $store->getCurrentCurrency()->getOutputFormat()), 'optionPrices' => $this->getOptionPrices(), 'prices' => [ 'oldPrice' => [ 'amount' => $this->_registerJsPrice($regularPrice->getAmount()->getValue()), ], 'basePrice' => [ 'amount' => $this->_registerJsPrice( $finalPrice->getAmount()->getBaseAmount() ), ], 'finalPrice' => [ 'amount' => $this->_registerJsPrice($finalPrice->getAmount()->getValue()), ], ], 'productId' => $currentProduct->getId(), 'is_salable' => $this->getIsSalable($this->getAllowProducts()), 'chooseText' => __('Choose an Option....'), 'images' => isset($options['images']) ? $options['images'] : [], 'index' => isset($options['index']) ? $options['index'] : [], ]; if ($currentProduct->hasPreconfiguredValues() && !empty($attributesData['defaultValues'])) { $config['defaultValues'] = $attributesData['defaultValues']; } $config = array_merge($config, $this->_getAdditionalConfig()); return $this->jsonEncoder->encode($config); } public function getOptions($currentProduct, $allowedProducts) { $options = []; $allowAttributes = $this->getAllowAttributes($currentProduct); foreach ($allowedProducts as $product) { $productId = $product->getId(); foreach ($allowAttributes as $attribute) { $productAttribute = $attribute->getProductAttribute(); $productAttributeId = $productAttribute->getId(); $attributeValue = $product->getData($productAttribute->getAttributeCode()); $options[$productAttributeId][$attributeValue][] = $productId; $options['index'][$productId][$productAttributeId] = $attributeValue; } } return $options; } public function getIsSalable($allowedProducts) { $options = []; $allowAttributes = $this->getAllowAttributes($allowedProducts); foreach ($allowedProducts as $product) { foreach ($allowAttributes as $attribute) { $productAttribute = $attribute->getProductAttribute(); $productAttributeId = $productAttribute->getId(); $attributeValue = $product->getData($productAttribute->getAttributeCode()); if (!$product->isSalable()) { $options[] = array("product_id"=>$product->getId(),"attribute_value"=>$attributeValue,"product_attribute_id"=>$productAttributeId); } } } return $options; } } |
Step 3: After that, we need to create a “requirejs-config.js” file inside the extension on the following path.
app\code\Vendor\Extension\view\frontend
Now, add the below code
1 2 3 4 5 6 7 |
var config = { map: { '*': { configurable:'Vendor_Extension/js/configurable', } } }; |
Step 4: After that, we need to create a “configurable.js” file inside the extension on the following path.
app\code\Vendor\Extension\view\frontend\web\js
And add the code as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
define([ 'jquery', 'underscore', 'mage/template', 'mage/translate', 'priceUtils', 'priceBox', 'jquery-ui-modules/widget', 'jquery/jquery.parsequery' ], function ($, _, mageTemplate, $t, priceUtils) { 'use strict'; $.widget('mage.configurable', { options: { superSelector: '.super-attribute-select', selectSimpleProduct: '[name="selected_configurable_option"]', priceHolderSelector: '.price-box', spConfig: {}, state: {}, priceFormat: {}, optionTemplate: '<%- data.label %>' + '<% if (typeof data.finalPrice.value !== "undefined") { %>' + ' <%- data.finalPrice.formatted %>' + '<% } %>', mediaGallerySelector: '[data-gallery-role=gallery-placeholder]', mediaGalleryInitial: null, slyOldPriceSelector: '.sly-old-price', normalPriceLabelSelector: '.normal-price .price-label', /** * Defines the mechanism of how images of a gallery should be * updated when user switches between configurations of a product. * * As for now value of this option can be either 'replace' or 'prepend'. * * @type {String} */ gallerySwitchStrategy: 'replace', tierPriceTemplateSelector: '#tier-prices-template', tierPriceBlockSelector: '[data-role="tier-price-block"]', tierPriceTemplate: '' }, /** * Creates widget * @private */ _create: function () { // Initial setting of various option values this._initializeOptions(); // Override defaults with URL query parameters and/or inputs values this._overrideDefaults(); // Change events to check select reloads this._setupChangeEvents(); // Fill state this._fillState(); // Setup child and prev/next settings this._setChildSettings(); // Setup/configure values to inputs this._configureForValues(); $(this.element).trigger('configurable.initialized'); }, /** * Initialize tax configuration, initial settings, and options values. * @private */ _initializeOptions: function () { var options = this.options, gallery = $(options.mediaGallerySelector), priceBoxOptions = $(this.options.priceHolderSelector).priceBox('option').priceConfig || null; if (priceBoxOptions && priceBoxOptions.optionTemplate) { options.optionTemplate = priceBoxOptions.optionTemplate; } if (priceBoxOptions && priceBoxOptions.priceFormat) { options.priceFormat = priceBoxOptions.priceFormat; } options.optionTemplate = mageTemplate(options.optionTemplate); options.tierPriceTemplate = $(this.options.tierPriceTemplateSelector).html(); options.settings = options.spConfig.containerId ? $(options.spConfig.containerId).find(options.superSelector) : $(options.superSelector); options.values = options.spConfig.defaultValues || {}; options.parentImage = $('[data-role=base-image-container] img').attr('src'); this.inputSimpleProduct = this.element.find(options.selectSimpleProduct); gallery.data('gallery') ? this._onGalleryLoaded(gallery) : gallery.on('gallery:loaded', this._onGalleryLoaded.bind(this, gallery)); }, /** * Override default options values settings with either URL query parameters or * initialized inputs values. * @private */ _overrideDefaults: function () { var hashIndex = window.location.href.indexOf('#'); if (hashIndex !== -1) { this._parseQueryParams(window.location.href.substr(hashIndex + 1)); } if (this.options.spConfig.inputsInitialized) { this._setValuesByAttribute(); } this._setInitialOptionsLabels(); }, /** * Parse query parameters from a query string and set options values based on the * key value pairs of the parameters. * @param {*} queryString - URL query string containing query parameters. * @private */ _parseQueryParams: function (queryString) { var queryParams = $.parseQuery({ query: queryString }); $.each(queryParams, $.proxy(function (key, value) { this.options.values[key] = value; }, this)); }, /** * Override default options values with values based on each element's attribute * identifier. * @private */ _setValuesByAttribute: function () { this.options.values = {}; $.each(this.options.settings, $.proxy(function (index, element) { var attributeId; if (element.value) { attributeId = element.id.replace(/[a-z]*/, ''); this.options.values[attributeId] = element.value; } }, this)); }, /** * Set additional field with initial label to be used when switching between options with different prices. * @private */ _setInitialOptionsLabels: function () { $.each(this.options.spConfig.attributes, $.proxy(function (index, element) { $.each(element.options, $.proxy(function (optIndex, optElement) { this.options.spConfig.attributes[index].options[optIndex].initialLabel = optElement.label; }, this)); }, this)); }, /** * Set up .on('change') events for each option element to configure the option. * @private */ _setupChangeEvents: function () { $.each(this.options.settings, $.proxy(function (index, element) { $(element).on('change', this, this._configure); }, this)); }, /** * Iterate through the option settings and set each option's element configuration, * attribute identifier. Set the state based on the attribute identifier. * @private */ _fillState: function () { $.each(this.options.settings, $.proxy(function (index, element) { var attributeId = element.id.replace(/[a-z]*/, ''); if (attributeId && this.options.spConfig.attributes[attributeId]) { element.config = this.options.spConfig.attributes[attributeId]; element.attributeId = attributeId; this.options.state[attributeId] = false; } }, this)); }, /** * Set each option's child settings, and next/prev option setting. Fill (initialize) * an option's list of selections as needed or disable an option's setting. * @private */ _setChildSettings: function () { var childSettings = [], settings = this.options.settings, index = settings.length, option; while (index--) { option = settings[index]; if (index) { option.disabled = true; } else { this._fillSelect(option); } _.extend(option, { childSettings: childSettings.slice(), prevSetting: settings[index - 1], nextSetting: settings[index + 1] }); childSettings.push(option); } }, /** * Setup for all configurable option settings. Set the value of the option and configure * the option, which sets its state, and initializes the option's choices, etc. * @private */ _configureForValues: function () { if (this.options.values) { this.options.settings.each($.proxy(function (index, element) { var attributeId = element.attributeId; element.value = this.options.values[attributeId] || ''; this._configureElement(element); }, this)); } }, /** * Event handler for configuring an option. * @private * @param {Object} event - Event triggered to configure an option. */ _configure: function (event) { event.data._configureElement(this); }, /** * Configure an option, initializing it's state and enabling related options, which * populates the related option's selection and resets child option selections. * @private * @param {*} element - The element associated with a configurable option. */ _configureElement: function (element) { this.simpleProduct = this._getSimpleProductId(element); if (element.value) { this.options.state[element.config.id] = element.value; if (element.nextSetting) { element.nextSetting.disabled = false; this._fillSelect(element.nextSetting); this._resetChildren(element.nextSetting); } else { if (!!document.documentMode) { //eslint-disable-line this.inputSimpleProduct.val(element.options[element.selectedIndex].config.allowedProducts[0]); } else { this.inputSimpleProduct.val(element.selectedOptions[0].config.allowedProducts[0]); } } } else { this._resetChildren(element); } this._reloadPrice(); this._displayRegularPriceBlock(this.simpleProduct); this._displayTierPriceBlock(this.simpleProduct); this._displayNormalPriceLabel(); this._changeProductImage(); }, /** * Change displayed product image according to chosen options of configurable product * * @private */ _changeProductImage: function () { var images, initialImages = this.options.mediaGalleryInitial, galleryObject = $(this.options.mediaGallerySelector).data('gallery'); if (!galleryObject) { return; } images = this.options.spConfig.images[this.simpleProduct]; if (images) { images = this._sortImages(images); if (this.options.gallerySwitchStrategy === 'prepend') { images = images.concat(initialImages); } images = $.extend(true, [], images); images = this._setImageIndex(images); galleryObject.updateData(images); $(this.options.mediaGallerySelector).AddFotoramaVideoEvents({ selectedOption: this.simpleProduct, dataMergeStrategy: this.options.gallerySwitchStrategy }); } else { galleryObject.updateData(initialImages); $(this.options.mediaGallerySelector).AddFotoramaVideoEvents(); } }, /** * Sorting images array * * @private */ _sortImages: function (images) { return _.sortBy(images, function (image) { return image.position; }); }, /** * Set correct indexes for image set. * * @param {Array} images * @private */ _setImageIndex: function (images) { var length = images.length, i; for (i = 0; length > i; i++) { images[i].i = i + 1; } return images; }, /** * For a given option element, reset all of its selectable options. Clear any selected * index, disable the option choice, and reset the option's state if necessary. * @private * @param {*} element - The element associated with a configurable option. */ _resetChildren: function (element) { if (element.childSettings) { _.each(element.childSettings, function (set) { set.selectedIndex = 0; set.disabled = true; }); if (element.config) { this.options.state[element.config.id] = false; } } }, /** * 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, allowedProductsByOption, allowedProductsAll, i, j, finalPrice = parseFloat(this.options.spConfig.prices.finalPrice.amount), optionFinalPrice, optionPriceDiff, optionPrices = this.options.spConfig.optionPrices, allowedOptions = [], indexKey, allowedProductMinPrice, allowedProductsAllMinPrice; 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 (indexKey in this.options.spConfig.index) { /* eslint-disable max-depth */ if (this.options.spConfig.index.hasOwnProperty(indexKey)) { allowedOptions = allowedOptions.concat(_.values(this.options.spConfig.index[indexKey])); } } if (prevConfig) { var allowedProductsByOption = {}; var allowedProductsAll = []; for (i = 0; i < options.length; i++) { /* eslint-disable max-depth */ 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) { if (!allowedProductsByOption[i]) { allowedProductsByOption[i] = []; } allowedProductsByOption[i].push(options[i].products[j]); allowedProductsAll.push(options[i].products[j]); } } } if (typeof allowedProductsAll[0] !== 'undefined' && typeof optionPrices[allowedProductsAll[0]] !== 'undefined') { allowedProductsAllMinPrice = this._getAllowedProductWithMinPrice(allowedProductsAll); finalPrice = parseFloat(optionPrices[allowedProductsAllMinPrice].finalPrice.amount); } } for (i = 0; i < options.length; i++) { allowedProducts = prevConfig ? allowedProductsByOption[i] : options[i].products.slice(0); optionPriceDiff = 0; if(allowedProducts){ if (typeof optionPrices[allowedProducts[0]] !== 'undefined') { allowedProductMinPrice = this._getAllowedProductWithMinPrice(allowedProducts); optionFinalPrice = parseFloat(optionPrices[allowedProductMinPrice].finalPrice.amount); optionPriceDiff = optionFinalPrice - finalPrice; options[i].label = options[i].initialLabel; if (optionPriceDiff !== 0) { options[i].label += ' ' + priceUtils.formatPrice( optionPriceDiff, this.options.priceFormat, true ); } } } if(allowedProducts){ if (allowedProducts.length > 0 || _.include(allowedOptions, options[i].id)) { options[i].allowedProducts = allowedProducts; element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id); /*---Customize Start----*/ var custom_option=[]; for(var p = 0; p < this.options.spConfig.is_salable.length; p++){ console.log(allowedProducts[0]+"-"+this.options.spConfig.is_salable[p]['product_id']); if(this.options.spConfig.is_salable[p]['attribute_value']){ if(options[i].id==this.options.spConfig.is_salable[p]['attribute_value'] && allowedProducts[0]==this.options.spConfig.is_salable[p]['product_id']){ custom_option=options[i].id; } } } /*---Customize End----*/ if (typeof options[i].price !== 'undefined') { element.options[index].setAttribute('price', options[i].price); } console.log("length :"+allowedProducts.length+"-"+custom_option+"=="+options[i].id); if (allowedProducts.length === 0) { element.options[index].disabled = true; }else if(allowedProducts.length === 1 && custom_option==options[i].id){ element.options[index].disabled = true; } element.options[index].config = options[i]; index++; } } /* eslint-enable max-depth */ } } }, /** * Generate the label associated with a configurable option. This includes the option's * label or value and the option's price. * @private * @param {*} option - A single choice among a group of choices for a configurable option. * @return {String} The option label with option value and price (e.g. Black +1.99) */ _getOptionLabel: function (option) { return option.label; }, /** * Removes an option's selections. * @private * @param {*} element - The element associated with a configurable option. */ _clearSelect: function (element) { var i; for (i = element.options.length - 1; i >= 0; i--) { element.remove(i); } }, /** * Retrieve the attribute options associated with a specific attribute Id. * @private * @param {Number} attributeId - The id of the attribute whose configurable options are sought. * @return {Object} Object containing the attribute options. */ _getAttributeOptions: function (attributeId) { if (this.options.spConfig.attributes[attributeId]) { return this.options.spConfig.attributes[attributeId].options; } }, /** * Reload the price of the configurable product incorporating the prices of all of the * configurable product's option selections. */ _reloadPrice: function () { $(this.options.priceHolderSelector).trigger('updatePrice', this._getPrices()); }, /** * Get product various prices * @returns {{}} * @private */ _getPrices: function () { var prices = {}, elements = _.toArray(this.options.settings), allowedProduct; _.each(elements, function (element) { var selected = element.options[element.selectedIndex], config = selected && selected.config, priceValue = {}; if (config && config.allowedProducts.length === 1) { priceValue = this._calculatePrice(config); } else if (element.value) { allowedProduct = this._getAllowedProductWithMinPrice(config.allowedProducts); priceValue = this._calculatePrice({ 'allowedProducts': [ allowedProduct ] }); } if (!_.isEmpty(priceValue)) { prices.prices = priceValue; } }, this); return prices; }, /** * Get product with minimum price from selected options. * * @param {Array} allowedProducts * @returns {String} * @private */ _getAllowedProductWithMinPrice: function (allowedProducts) { var optionPrices = this.options.spConfig.optionPrices, product = {}, optionMinPrice, optionFinalPrice; _.each(allowedProducts, function (allowedProduct) { optionFinalPrice = parseFloat(optionPrices[allowedProduct].finalPrice.amount); if (_.isEmpty(product) || optionFinalPrice < optionMinPrice) { optionMinPrice = optionFinalPrice; product = allowedProduct; } }, this); return product; }, /** * Returns prices for configured products * * @param {*} config - Products configuration * @returns {*} * @private */ _calculatePrice: function (config) { var displayPrices = $(this.options.priceHolderSelector).priceBox('option').prices, newPrices = this.options.spConfig.optionPrices[_.first(config.allowedProducts)]; _.each(displayPrices, function (price, code) { if (newPrices[code]) { displayPrices[code].amount = newPrices[code].amount - displayPrices[code].amount; } }); return displayPrices; }, /** * Returns Simple product Id * depending on current selected option. * * @private * @param {HTMLElement} element * @returns {String|undefined} */ _getSimpleProductId: function (element) { // TODO: Rewrite algorithm. It should return ID of // simple product based on selected options. var allOptions = element.config.options, value = element.value, config; config = _.filter(allOptions, function (option) { return option.id === value; }); config = _.first(config); return _.isEmpty(config) ? undefined : _.first(config.allowedProducts); }, /** * Show or hide regular price block * * @param {*} optionId * @private */ _displayRegularPriceBlock: function (optionId) { var shouldBeShown = true; _.each(this.options.settings, function (element) { if (element.value === '') { shouldBeShown = false; } }); if (shouldBeShown && this.options.spConfig.optionPrices[optionId].oldPrice.amount !== this.options.spConfig.optionPrices[optionId].finalPrice.amount ) { $(this.options.slyOldPriceSelector).show(); } else { $(this.options.slyOldPriceSelector).hide(); } $(document).trigger('updateMsrpPriceBlock', [ optionId, this.options.spConfig.optionPrices ] ); }, /** * Show or hide normal price label * * @private */ _displayNormalPriceLabel: function () { var shouldBeShown = false; _.each(this.options.settings, function (element) { if (element.value === '') { shouldBeShown = true; } }); if (shouldBeShown) { $(this.options.normalPriceLabelSelector).show(); } else { $(this.options.normalPriceLabelSelector).hide(); } }, /** * Callback which fired after gallery gets initialized. * * @param {HTMLElement} element - DOM element associated with gallery. */ _onGalleryLoaded: function (element) { var galleryObject = element.data('gallery'); this.options.mediaGalleryInitial = galleryObject.returnCurrentImages(); }, /** * Show or hide tier price block * * @param {*} optionId * @private */ _displayTierPriceBlock: function (optionId) { var options, tierPriceHtml; if (typeof optionId != 'undefined' && this.options.spConfig.optionPrices[optionId].tierPrices != [] // eslint-disable-line eqeqeq ) { options = this.options.spConfig.optionPrices[optionId]; if (this.options.tierPriceTemplate) { tierPriceHtml = mageTemplate(this.options.tierPriceTemplate, { 'tierPrices': options.tierPrices, '$t': $t, 'currencyFormat': this.options.spConfig.currencyFormat, 'priceUtils': priceUtils }); $(this.options.tierPriceBlockSelector).html(tierPriceHtml).show(); } } else { $(this.options.tierPriceBlockSelector).hide(); } } }); return $.mage.configurable; }); |
Step 5: After that, from the Magento Admin Panel navigate to,
Stores → Configuration → Catalog → Inventory → Stock Options
Set “Yes” to the “Display Out of Stock Products” field.
Once you implement all the above steps, the Out of Stock Options will be displayed for the Configurable Products Dropdown as shown below.
Conclusion:
This way you can Show Out of Stock Options for Configurable Products Dropdown in Magento 2. Moreover, show out of stock product price for the awareness of customers. If you have any queries, let me know in the comment part. Do share the article with your friends and colleagues. Stay updated with us!
Happy Coding!
Unfortunately not working at all on M2.4.5-p1
Hi
As the blog is old, there are chances it may not be working with latest magento version.
We will try to update the blog ASAP with latest magento version compatibility.
did you have time to do that or is it still old code?
If you face any issue into specific version, you can contact on support@magecomp.com
Hello Dhiren Sir,
Is there any way to display child product’s Price if option out of stock while changing the swatches value on the configurable products?
It would be great if you comment regarding this.
Yes, you need to further customise the code according to requirement, for more customisation you can contact on support@magecomp.com
Have any solution for swatches product when out of stock option on configurable product
For more customisation you can contact on support@magecomp.com
Hello,
I have tried this solution but it’s not working,
I am using magento version 2.3.4 and this solution is not working even in the luma theme.
Confirm this, It do not conflict with anything other into same site.