简体   繁体   English

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

[英]Select2: Update option after selecting new tag

I implemented a tagging system where you can choose from existing tags or add new tags. 我实现了一个标签系统,您可以在其中选择现有标签或添加新标签。 After a new tag has been selected it will persisted using an AJAX call. 选择一个新标签后,它将使用AJAX调用保留下来。

For achieving this I use the callback createTag and the event select2:select . 为此,我使用了回调createTag和事件select2:select Because I like to create the tag only when it is selected I do an AJAX call for this if the event select2:select gets triggered. 因为我只想在选择标记后才创建标记,所以如果触发了select2:select事件,我将为此进行AJAX调用。

The problem is that I need to update the already created option of select2 with the ID I get from persisting my new tag to the database. 问题是我需要使用从将新标签持久保存到数据库中获得的ID更新select2的已创建选项。 What's the cleanest solution for this? 最干净的解决方案是什么?

Here's what I have: 这是我所拥有的:

$('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");
 });

My problem was that I did not add the new tag as an <option> tag to the native select field. 我的问题是我没有将新标签作为<option>标签添加到本机选择字段中。

This is necessary because select2 checks for the values set trough select2.val(values) if an <option> tag with this value does exist. 这是必要的,因为select2将检查是否存在通过select2.val(values)设置的select2.val(values)如果确实存在具有该值的<option>标记。 If not select2 silently throws the value out of the array and sets the array of values which have a corresponding option tag in the underlying select field. 如果没有,则select2默默地将值从数组中抛出,并设置在基础选择字段中具有相应选项标签的值的数组。

So this is how it works correct now (for select2 4.0.x): 因此,这是现在正确的工作方式(对于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');
 });

The minimal AJAX response (JSON format) has to look like this: 最小的AJAX响应(JSON格式)必须如下所示:

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

You may add additional data to each result for let's say own rendering of the result list with additional data in it. 您可以在每个结果中添加其他数据,例如,自己渲染结果列表,并在其中添加其他数据。

Just to update: 只是更新:

The new syntax is 新的语法是

e.params.args.data.id

not

e.params.data.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM