You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony中PUGX bundle搭配Select2 3.5.2报toUpperCase未定义错误

问题原因

  • Select2 3.5.2版本默认要求选项数据结构中必须包含text字段用于文本匹配和展示,你当前Twig返回的JSON每一项只有id、label、value三个字段,缺少text字段,Select2在做输入匹配时试图读取不存在的字段值做大小写转换,就触发了这个报错。
  • 你配置的formatNoMatches、formatSearching这类回调命名,在3.5.2-browserify版本的Select2中存在命名空间兼容性问题,和PUGXAutoCompleterBundle的封装逻辑冲突。

解决步骤

1. 修改Twig的JSON返回结构,补充text字段

给每一项增加text字段,值和label保持一致即可:

[{% for postalCode in postalCodes -%}
    {{ {id: postalCode.id, label: postalCode.zipcode ~ ' ' ~ postalCode.name, value: postalCode.zipcode ~ ' ' ~ postalCode.name, text: postalCode.zipcode ~ ' ' ~ postalCode.name}|json_encode|raw }}
    {%- if not loop.last %},
    {% endif -%}
 {%- endfor %}
]

2. 调整JS中的Select2配置项

移除旧版format前缀的配置,改用3.5.2-browserify版本兼容的写法:

import $ from 'jquery';
import 'select2/select2';
import '@pugx/autocompleter-bundle/js/autocompleter-select2';

$('#postal_code_search_zipcode').autocompleter({
    url_list: '/postalCode_search',
    url_get: '/postalCode_get/',
    otherOptions: {
        minimumInputLength: 3,
        language: {
            noResults: function () {
                return 'Pas trouvé';
            },
            searching: function () {
                return 'Je cherche';
            },
            inputTooShort: function (args) {
                return 'Insérer au minimum les 3 premiers chiffre';
            }
        }
    }
})

3. 兼容兜底方案

如果上述修改后仍报错,可在otherOptions中追加字段映射配置,强制指定Select2读取label作为匹配字段:

ajax: {
    processResults: function (data) {
        return {
            results: data.map(function (item) {
                item.text = item.label;
                return item;
            })
        };
    }
}

内容的提问来源于stack exchange,提问作者Micka Bup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:45:04