Select2:选择新标签后更新选项

Select2: Update option after selecting new tag

我实施了一个标签系统,您可以在其中选择现有标签或添加新标签。选择新标签后,它将使用 AJAX 调用保留。

为了实现这一点,我使用回调 createTag 和事件 select2:select。因为我喜欢只在选择标签时创建标签,所以如果事件 select2:select 被触发,我会为此调用 AJAX。

问题是我需要使用从将新标签持久保存到数据库中获得的 ID 更新已创建的 select2 选项。最干净的解决方案是什么?

这是我的:

$('select.tags').select2({
     tags: true,
     ajax: {
         url: '{{ path('tag_auto_complete') }}',
         processResults: function (data) {
             return {
                 results: data.items,
                 pagination: {
                     more: false
                 }
             };
         }
     },
     createTag: function (tag) {
         return {
             id: tag.term, // <-- this one should get exchanged after persisting the new tag
             text: tag.term,
             tag: true
         };
     }
 }).on('select2:select', function (evt) {
     if(evt.params.data.tag == false) {
         return;
     }

     $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
        // ----> Here I need to update the option created in "createTag" with the ID
        option_to_update.value = data.id;

     }, "json");
 });

我的问题是我没有将新标签作为 <option> 标签添加到原生 select 字段。

这是必要的,因为 select2 检查通过 select2.val(values) 设置的值是否存在具有此值的 <option> 标签。如果不是 select2,则静默将值从数组中抛出,并在基础 select 字段中设置具有相应选项标记的值数组。

这就是它现在的正确工作方式(对于 select2 4.0.x):

$('select.tags').select2({
     tags: true,
     ajax: {
         url: '{{ path('tag_auto_complete') }}',
         processResults: function (data) {
             return {
                 results: data.items,
                 pagination: {
                     more: false
                 }
             };
         }
     },
     createTag: function (tag) {
         return {
             id: tag.term,
             text: tag.term,
             tag: true
         };
     }
 }).on('select2:select', function (evt) {
     if(evt.params.data.tag == false) {
         return;
     }

     var select2Element = $(this);

     $.post('{{ path('tag_crrate_auto_complete') }}', { name: evt.params.data.text }, function( data ) {
        // Add HTML option to select field
        $('<option value="' + data.id + '">' + data.text + '</option>').appendTo(select2Element);

        // Replace the tag name in the current selection with the new persisted ID
        var selection = select2Element.val();
        var index = selection.indexOf(data.text);            

        if (index !== -1) {
            selection[index] = data.id.toString();
        }

        select2Element.val(selection).trigger('change');

     }, 'json');
 });

最小 AJAX 响应(JSON 格式)必须如下所示:

[
    {'id': '1', 'text': 'foo'},
    {'id': '2', 'text': 'bar'},
    {'id': '3', 'text': 'baz'}
]

您可以向每个结果添加额外的数据,比方说自己呈现包含额外数据的结果列表。

刚刚更新:

新语法是

e.params.args.data.id

没有

e.params.data.id