Update Tags with Select2 Multiple

Hi! I tried to implement this script in my website’s project (CRUD).
I used the multiple version with tags.

I understood perfectly how to store data on Db starting from “New” Input, but how can I do if I want to change this data retrieving them from db?

How can I my send JSON from db-php-ajax to Select2 to obtain the “compiled” input box form with the result of updating this tags ?
thank you for your time, best regards.

Let me make sure I understand what you want to do:

  1. User enters some “new” data in the Select2 (an item that isn’t in the Select2’s current data set), creating a tag.
  2. Your code stores that tag in your (remote) database.
  3. Now you want the new data to appear in the Select2 dropdown.

Assuming that is correct, I can think of two options. After you have successfully stored the tag in your database:

  1. You can manually create a new item in the Select2 that contains the value of the tag as its “value” property.
  2. You can requery all of the data from your remote database, load it into a JavaScript array of the proper form and re-initialize the Select2 with the new data array.

Hi John, thanks for your reply.

Yes, imagine that on my db I have a table with this data:

  1. code 0022 | Red
  2. code 0045 | Yellow
  3. code 0065 | Green

In my “Select2 multiple tag” I would like that a call to Ajax/php send to Javascript the precompiled data and user seen [ red ] [ yellow ] [ green] but the value of these tags are 0022, 0045, 0065

JSON file is correct like this?

{
“results”: [
{
“id”: 0022,
“text”: “Red”
},
{
“id”: 0045,
“text”: “Yellow”
},
{
“id”: 0065,
“text”: “Green”
}
]
}

What type of call I must do in javascript to inizialize Select2 with precompiled tag data?

The result should be like this:

Cattura

and when a user click to update this, can see all the other “colors” that’s are not yet served

Hi, ddstaff–

Thanks for the extra details. How you solve this depends on how you’re getting the data into your Select2. Your goal is to have those “new” items selected in the Select2 after you’ve updated the database on the server side and returned the updated data set to your application.

  1. If you’re calling your AJAX/php endpoint directly from the Select2 using its AJAX feature, then your data format is mostly correct (you’ll want to make your id values strings too, otherwise JavaScript won’t preserve the leading zeros).

    When using the Select2 AJAX feature, the Select2 does not actually create <option> elements until the user makes a selection from the dropdown (or creates a tag). In fact, it doesn’t even retrieve any data from the remote data source until the user starts typing. So, to display the new tags “precompiled” (in other words, pre-selected), you must manually generate an <option value="..." selected>....</option> tag for each of the values you want to display. There is more information about this approach here: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 (you should read that entire page, not just the section I linked to, but that section is the specific details for this situation).

    Their suggestion is to have a separate remote endpoint that can give you the values of the items you want to pre-select; however, if you can remember those values (locally) from when the user previously entered them, you can use that data to generate your <option ... selected> tags.

  1. If you’re loading the item data from your AJAX/php endpoint separately (for instance, using $.json() to pull the data into a local array and then initializing the Select2 with that array (via the data configuration property), then your AJAX/php endpoiunt can simply include the “selected” property on the items that match the “new” entries:

    [
        { id: "0022", text: "Red", selected: true },
        { id: "0045", text: "Green", selected: true },
        { id: "0065", text: "Blue", selected: true },
         /*  ... all the other data values in the list ... */
    ]
    

    (Note that you don’t wrap this array in an object with the results property; that’s only when you’re using Select2’s AJAX feature.)

    Once you get your data array from your AJAX/php endpoint, you re-initialize your Select2 with it: $('.selector-for-your-select').select2({data: yourDataArray}); Select2 will automatically pre-select those items in the array that have the selected property set to true.

I hope that’s not too confusing. If you’re still unsure about how to proceed, let me know which method you’re using to get the data for your Select2, and I’ll try to give you some more specific guidance.

Good Day, I Need some help with this I’m totally a newbie and need some guidance, on how to proceed.

here is my code

<?php $args = array( 'order' => 'ASC', 'hide_empty' => $hide_empty, 'include' => $ids, 'posts_per_page' =>'-1' ); $product_categories = get_terms( 'product_cat', $args ); echo ''; foreach( $product_categories as $category ){ // echo "slug ) . "'>" . esc_html( $category->name ) . ""; echo "name ) . "'>" . esc_html( $category->name ) . ""; } echo "
"; ?> <?php echo''; ?>
jQuery(function () {
jQuery(".js-example-basic-multiple").select2({
    tags: true,
    tokenSeparators: [","],
    templateSelection: function (state) {
        let stateTemplate = jQuery("<span></span>");

        if (state.newTag) {
            stateTemplate.addClass("custom");
        } else {
            stateTemplate.addClass("normal");
        }

        // Use .text() instead of HTML string concatenation to avoid script injection issues
        stateTemplate.text(state.text);

        return stateTemplate;
    },
    createTag: function (params) {
        let term = jQuery.trim(params.term);

        if (term === "") {
            return null;
        }

        return {
	          id: term,
            text: term,
            newTag: true, // add additional parameters
        };
    },
});

jQuery(".js-example-basic-multiple").parent().find('.select2-search__field').val('<?php echo $crosssell.",";?>').trigger('keyup');

});

<?php echo '</script>';?>

I have changed the code since the last post. I can get it to show up now but the title is showing [object Object] and not the title as it should. Please any help will be appriciated

[object Object] is what JavaScript outputs when you try to use an object where a string is expected. If I understand your code and your description correctly, the “title” you’re referring to is the stateTemplate.text() value, which is being assigned the value of state.text.

Without seeing your data (the values being passed into the templateSelection callback), I can’t give you a more specific diagnosis.

One question I would ask is what you’re actually trying to accomplish with the code above? The example code you copied from the Select2 site has a very specific purpose; unless you’re trying to do that same thing, the code above is probably not what you need.

Hi, John Thank you for your feedback, I’m trying to implement select2 into Woocommerce I created a plugin that is a normal inputfield, where someone can add the Categories Manually. but I have changed that to be a dropdown (select field)with all the categories in the dropdown. now the dropdown works perfectly if you only select 1 Category, but I would like to select up to 3 different categories, that is why I decided to use the select 2 but my knowledge of select to is very limited even when I tried following the examples!

but let me see if I can get it all in order for you.
This script Calls for the Categories. as a select filed

<?php $args = array( 'order' => 'ASC', 'hide_empty' => $hide_empty, 'include' => $ids, 'posts_per_page' =>'-1' ); $product_categories = get_terms( 'product_cat', $args ); echo ''; foreach( $product_categories as $category ){ // echo "slug ) . "'>" . esc_html( $category->name ) . ""; echo "name ) . "'>" . esc_html( $category->name ) . ""; } echo "
"; ?>

the output is this:
< select class=“js-example-basic-multiple select2-hidden-accessible” name=“crosssell” multiple="" tabindex="-1" aria-hidden=“true”>
< option value=“3 In One Oil”>3 In One Oil< /option>
< option value=“Angle Grinder”>Angle Grinder< /option>
< option value=“Anti Spat Spray Silicone & Non Silicone”>Anti Spat Spray Silicone & Non Silicone< /option>
< option value=“Assorted Bolts & Nuts”>Assorted Bolts & Nuts< /option>
< option value=“Assorted Cable Clips”>Assorted Cable Clips< /option>
< option value=“Assorted Flat Washers”>Assorted Flat Washers< /option>
< option value=“Assorted Hex Nuts”>Assorted Hex Nuts< /option>
< option value=“Assorted Machine Screws”>Assorted Machine Screws< /option>
< /select>
the select field is a very long one so I shorten it a lot

Now I can get it to look like its working by selecting lets say 3 categories but it only post the last 1

but when I change it back to input field text and type the categories is separated by a comma it works

PHP script for that is
if ( isset( $_POST[‘crosssell’] ) && in_array($taxonomy, $pages)) {
update_term_meta( $term_id, ‘crosssell’, sanitize_text_field($_POST[‘crosssell’]) );
}
the when I click edit to remove selected it gives me the error as above [object Object] if you need more info please let me know

I am not a PHP expert, and I suspect that is the issue with receiving the multiple items you’ve selected in your Select2 widget. Check out html - How to get multiple selected values of select box in php? - Stack Overflow for details about how to specify a multi-select form element and how to process the selected values with PHP.

Also, in your <select> element, the multiple attribute should either have no value at all (i.e., do not specify =""), or it should have the value “multiple” (i.e., <select ... multiple="multiple">).