I am using Select2 in my web application. I load Select2 boxes in Ajax. When the check is not performed, all inputs are filled, as before, except for the Select2 field. How to restore old value after unsuccessful form validation? My bet was to use Request::old('x') , but this inserts a value (in my case the user id) instead of the highlighted text. So, for example, the text John will become 27 in the selectbox. How can I return the text?
<select id="customer" name="customer" class="searchselect searchselectstyle"> </select>
js:
token = '{{csrf_token()}}'; $(".searchselect").select2({ ajax: { dataType: "json", type: "POST", data: function (params) { return { term: params.term, '_token': token, 'data' : function(){ var result = []; var i = 1; $('.searchselect').each(function(){ result[i] = $(this).val(); i++; }); return result; } }; }, url: function() { var type = $(this).attr('id'); return '/get' + type; }, cache: false, processResults: function (data) { return { results: data }; } } });
Edit
The only (dirty) solution I've found so far is this:
<select id="customer" name="customer" class="searchselect searchselectstyle"> @if(Request::old('customer') != NULL) <option value="{{Request::old('customer')}}">{{$customers->where('id', intval(Request::old('customer')))->first()->name}}</option> @endif </select>
$customers is a list of all customers, so this means that for each Select2 window I need to request a large list of items to make it work. It will be rather inefficient if we talk about thousands of lines in the Select2 window.
I think there should be a better solution. Who can help me?
ajax laravel laravel-5 jquery-select2
Markinson
source share