djangokillen's avatar

Select2 tags - old input in Laravel?

Hi! I'm trying to make a tagging system, and for the visual tagging I've decided to go with Select2 as Jeffrey have featured it earlier on the site and I think it is very good. Everything works fine, but I don't really know how to go about populating the select input with the old values after the form has been submitted. This is my select input:

<select name="tags[]" id="tags" class="form-control" multiple data-fv-field="tags"></select>

If some other field has failed on submission, I want the tags to still be there. I hope I made myself clear, otherwise you can just ask further questions. Thanks.

0 likes
7 replies
djangokillen's avatar

So I've tried this:

@if (is_array(old('tags')))
         <select name="tags[]" id="tags" class="form-control" multiple data-fv-field="tags">
              @foreach (old('tags') as $tag)
                  <option value="{{ $tag }}" data-select2-tag="true">{{ $tag }}</option>
             @endforeach
        </select>
@else
     <select name="tags[]" id="tags" class="form-control" multiple data-fv-field="tags"></select>
@endif

But it just don't wanna work. Surely there's also a better way of doing this.

djangokillen's avatar
djangokillen
OP
Best Answer
Level 3

If anyone wonders, this is the code that solved it:

<select name="tags[]" id="tags" class="form-control" multiple>
    @if (is_array(old('tags')))
        @foreach (old('tags') as $tag)
            <option value="{{ $tag }}" selected="selected">{{ $tag }}</option>
        @endforeach
    @endif
 </select>

And jQuery:

$('#tags').select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',']
});
4 likes
Patroklo's avatar

Maaaaan, it should be a simpler way to user select2 in laravel. A wrapper could come handy

Please or to participate in this conversation.