成功时select2检索新创建的标签ID

时间:2022-11-27 19:55:57

In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?

在select2中,我有通过AJAX加载的标签,如果在db中找不到标签,则用户可以选择创建新标签。问题是新标签在select2框中列为一个术语,而不是id(想要选择的内容 - 如果用户想要更新,则再次加载标签时会出现问题,因为只有术语而不是id存储在db)中。如果成功添加该术语,我怎样才能使select2接收ID并提交ID而不是标签名称/术语?

$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
    multiple: true,
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "framework/helpers/tags.php",
        dataType: "json",
        data: function(term) {
            return {
                term: term
            };
        },
        results: function(data) {
            return {
                results: data
            };
        }
    },
    createSearchChoice: function(term) {
        var text = term + (lastResults.some(function(r) {
            return r.text == term
        }) ? "" : " (new)");
        return {
            id: term,
            text: text
        };
    },
});
$('#project_tags').on("change", function(e) {
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
            var response = confirm("Do you want to add the new tag " + e.added.id + "?");
            if (response == true) {
                alert("Will now send new tag to server: " + e.added.id);
                $.ajax({
                    url: 'framework/helpers/tags.php',
                    data: {
                        action: 'add',
                        term: e.added.id
                    },
                    success: function(data) {

                    },
                    error: function() {
                        alert("error");
                    }
                });
            } else {
                console.log("Removing the tag");
                var selectedTags = $("#project_tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index, 1);
                if (selectedTags.length == 0) {
                    $("#project_tags").select2("val", "");
                } else {
                    $("#project_tags").select2("val", selectedTags);
                }
            }
        }
    }
});

});

});

Heres part of the switch that does the adding

这是交换机的一部分,用于添加

case 'add':
    if (isset($_GET['term'])) {
        $new_tag = escape($_GET['term']);
        if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
            // we need to send back the ID for the newly created tag
            $search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
            list($tag_id) = $search->fetch_row();
            echo $tag_id;
        } else {
            echo 'Failure';
        }
        exit();
    }
    break;

UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!

更新:我做了一些挖掘,让我感到困惑的是,select2输入似乎没有存储标签/术语的相关ID(见下文)。我知道我可以用成功回调来改变属性,但我不知道要改变什么!

成功时select2检索新创建的标签ID

1 个解决方案

#1


4  

As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.

正如您所说,您可以替换该值,这就是我的解决方案所做的。如果您搜索Chrome的Element Inspector,您将在Select2字段旁边看到一个id为project_tags且高度为1的输入。

The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:

奇怪的是Chrome的元素检查器没有显示输入的值,如下所示:

成功时select2检索新创建的标签ID

However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).

但是,你做一个console.log($(“#project_tags”)。val())输入有值(如图所示)。

So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:

因此,你可以简单地用id,在$('#project_tags')。on(“change”)函数中放置的ajax调用的success函数内替换新选项的文本。 ajax调用将是这样的:

$.ajax({
    url: 'framework/helpers/tags.php',
    data: {
        action: 'add',
        term: e.added.id
    },
    success: function(tag_id) {
        var new_val = $("#project_tags")
                        .val()
                        .replace(e.added.id, tag_id);
        $("#project_tags").val(new_val);
    },
    error: function() {
        alert("error");
    }
});

Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.

请注意,此解决方案不是防弹。例如,如果您选择了值为1的标记,并且用户插入了文本1,则会导致问题。

Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.

也许更好的选择是替换最后一个逗号右边的所有内容。但是,如果允许用户使用逗号创建标记,即使这可能会导致一些问题。

Let me know if you need any more information.

如果您需要更多信息,请与我们联系。

#1


4  

As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.

正如您所说,您可以替换该值,这就是我的解决方案所做的。如果您搜索Chrome的Element Inspector,您将在Select2字段旁边看到一个id为project_tags且高度为1的输入。

The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:

奇怪的是Chrome的元素检查器没有显示输入的值,如下所示:

成功时select2检索新创建的标签ID

However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).

但是,你做一个console.log($(“#project_tags”)。val())输入有值(如图所示)。

So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:

因此,你可以简单地用id,在$('#project_tags')。on(“change”)函数中放置的ajax调用的success函数内替换新选项的文本。 ajax调用将是这样的:

$.ajax({
    url: 'framework/helpers/tags.php',
    data: {
        action: 'add',
        term: e.added.id
    },
    success: function(tag_id) {
        var new_val = $("#project_tags")
                        .val()
                        .replace(e.added.id, tag_id);
        $("#project_tags").val(new_val);
    },
    error: function() {
        alert("error");
    }
});

Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.

请注意,此解决方案不是防弹。例如,如果您选择了值为1的标记,并且用户插入了文本1,则会导致问题。

Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.

也许更好的选择是替换最后一个逗号右边的所有内容。但是,如果允许用户使用逗号创建标记,即使这可能会导致一些问题。

Let me know if you need any more information.

如果您需要更多信息,请与我们联系。