Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 - Multiple tags not working

I'm trying to use Select2 (https://select2.github.io) to allow a user to type multiple tags into a field before submitting a form. In my Laravel PHP app, I'll then take those tags, determine if they exist and add them into a database.

My problem is that I can't seem to get Select2 to recognise there are multiple tags being entered by the user. When I interrogate the form data, I only see the LAST tag a user typed as opposed to ALL the tags.

My Select2 element is:

<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple">
</select>

and my JQuery is:

$(function() {
    $(".tags-field").select2({
        maximumSelectionLength: 3,
        tokenSeparators: [','],
    });
}

There are no Javascript errors and it works perfectly fine except I cannot detect ALL the tags.

like image 655
noobmaster69 Avatar asked Aug 15 '15 19:08

noobmaster69


1 Answers

To cause PHP to make all the selected choices available as an array, suffix your select name with a pair of square brackets, like this:

<select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple">

If this form is sent to a PHP program, the value of $_POST['tags'] will be an array. Note that the square brackets in the form control name aren't a part of the array key. You would process such a form like this:

<?php
$tags = $_POST['tags'];
// Note that $tags will be an array.
foreach ($tags as $t) {
    echo "$t<br />";
}
?>

References here: http://bbrown.kennesaw.edu/papers/php2.html

like image 62
Paul Vidal Avatar answered Sep 29 '22 08:09

Paul Vidal