Magento 2:仅存在一个可选选项时自动选中该选项
Magento 2 自动选中唯一可配置选项实现方案
方法一:前端JavaScript修改(快速适配)
针对下拉菜单选项
找到当前主题下的 catalog/product/view/type/options/configurable.phtml 文件,在文件末尾添加以下代码:
require(['jquery'], function($) { $(document).ready(function() { $('.super-attribute-select').each(function() { var $select = $(this); // 下拉框默认包含空选项,长度为2代表仅1个可选值 if ($select.find('option').length === 2) { $select.val($select.find('option:not([value=""])').val()).trigger('change'); } }); }); });
针对色板(Swatch)选项
推荐用mixins扩展核心JS文件,避免直接修改源码:
- 在自定义主题/模块的
requirejs-config.js中添加配置:
var config = { config: { mixins: { 'Magento_Swatches/js/swatch-renderer': { 'Your_Module/js/swatch-renderer-mixin': true } } } };
- 创建
swatch-renderer-mixin.js文件:
define(['jquery'], function($) { 'use strict'; return function(swatchRenderer) { return $.extend(swatchRenderer, { _RenderControls: function() { this._super(); var swatchAttrs = this.options.jsonConfig.attributes; $.each(swatchAttrs, function(attrId, attrData) { if (attrData.options.length === 1) { var optionId = attrData.options[0].id; $('.swatch-option.' + attrId + '-' + optionId).trigger('click'); } }); } }); }; });
方法二:自定义模块后端处理(稳定兼容)
通过修改可配置产品的JSON配置,让前端自动读取默认选中值,同时兼容下拉和色板:
- 创建自定义模块(示例:
Vendor/ConfigurableAutoSelect),在etc/frontend/di.xml中添加插件配置:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable"> <plugin name="vendor_configurable_autoselect" type="Vendor\ConfigurableAutoSelect\Plugin\ConfigurableBlockPlugin" sortOrder="10"/> </type> </config>
- 创建
Plugin/ConfigurableBlockPlugin.php文件:
<?php namespace Vendor\ConfigurableAutoSelect\Plugin; use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable; use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableType; class ConfigurableBlockPlugin { protected $configurableType; public function __construct(ConfigurableType $configurableType) { $this->configurableType = $configurableType; } public function afterGetJsonConfig(Configurable $subject, $result) { $config = json_decode($result, true); $product = $subject->getProduct(); $attributes = $this->configurableType->getConfigurableAttributes($product); foreach ($attributes as $attribute) { $attributeId = $attribute->getAttributeId(); $options = $attribute->getOptions(); if (count($options) === 1) { $config['attributes'][$attributeId]['default'] = $options[0]->getValueIndex(); } } return json_encode($config); } }
注意事项
- 修改主题文件前,务必复制到自定义主题目录,不要直接修改核心文件。
- 新增/修改静态文件后,执行
bin/magento setup:static-content:deploy刷新静态资源。 - 自定义模块需执行
bin/magento setup:upgrade完成安装。
内容的提问来源于stack exchange,提问作者User89798
相关产品推荐
相关产品推荐

