Laravel Select2 old login after verification

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?

+7
ajax laravel laravel-5 jquery-select2
source share
8 answers

I end up using a thread similar to yours. But my clip template uses the htmlcollection package.

Controller: -

Let's say you are in the create() method. When the validation fails, it redirects back to the creation page. On this page you can fill in the list.

 $customer_list = []; if(old('customer') != NULL){ $customer_list = [old('customer') => $customers->where('id', old('customer'))->first()->name]; } 

Type of blade:

 {{ Form::select('customer', $customer_list, null, ['class' => 'searchselect searchselectstyle', 'id' => 'customer']) }} 
+1
source share

Usually, to programmatically set select2, you expect to use the .val() method, followed by a call to .trigger('change') according to their documentation (and other requests like this in SO ). However, select2 has something in its documentation about pre-selecting parameters for remote sources .

Essentially, their proposal boils down to (after initializing your AJAX-driven <select> ):

  • make another AJAX call to the new API endpoint using the pre-selected identifier
  • dynamically create a new option and add to the base <select> from the promise function ( .then() ) after completing the AJAX call
    • can also use some of the usual jQuery callback chain functions for this
  • fires the change event
  • fires the select2:select event (and select2:select through the entire data object)

Assuming that you are already reconciling old data per session, Laravel provides convenient access to previously requested input in various ways, in particular these three:

  • static access through the Request class, for example. Request::old('customer') , as in OP
  • global old() helper , for example. old('customer') , which returns null if the old input for this field does not exist and can have a default value as the second parameter
  • using the old() method in the Request instance from the controller, for example. $request->old('customer')

The global helper method is most often suggested for use inside Blade templates, as in some other answers here, and is useful when you do not need to manipulate the value and you can simply connect it back with things like text inputs.

The last method probably gives you the answer you are looking for - instead of requesting the entire collection from within the view, you can either manipulate the collection from the controller (similar to OP, but should be better since it does not parse it in the view) or do another request from the controller based on the old identifier and get the necessary data without having to trawl the collection (less overhead):

 $old_customer = Customer::find($request->old('customer')); 

In any case, you have specific data available at your fingertips (as a view variable) before the blade template processes anything.

However, you choose to enter data, it will still follow the pattern suggested by select2:

  • get preselected data
  • create an option for him
  • trigger relevant events

The only difference is that you do not need to retrieve data from another API endpoint (unless you need / need other programmatic reasons).

+1
source share

Perhaps you can try (once the ajax call has ended):

 var oldCustomer = $('#customer > option[value={{ Request::old('customer') }}]'); if (oldCustomer.length > 0) { oldCustomer.attr('selected', 'selected'); } 
0
source share

Same problem; I use a similar solution: if the old $ id is set, I get the name, and I use it as a variable for presentation; Please note that I also forward the identifier, because I also used this method to pre-fill the form (coming from another place), but in this case only the name should be used, and for id {{old ('author_id')} } can be used in the view:

In the controller:

 elseif (($request->old('author_id') !== null) && ($request->old('author_id') != '')) { $my_author_id = $request->old('author_id'); $my_name = Author::find($my_author_id)->name; return view('admin/url_author.create', compact('my_name', 'my_author_id')); } 

And in the view (more precisely, in the partial used for the creation and publication):

 @if (isset($record)) // for use in edit case with laravelcollective) <select class="form-control js-data-author-ajax" id="author_id" name="author_id"> <option value="{{ $record->author_id }}">{{ $record->author->name }}</option> </select> @else @if (isset($my_name)) // old input after validation + pre-filling cases <select class="form-control js-data-author-ajax" id="author_id" name="author_id"> <option value="{{ $my_author_id }}">{{ $my_name }}</option> </select> @else // for create cases <select class="form-control js-data-auteur-ajax" id="auteur_id" name="auteur_id"> <option></option> </select> @endif @endif 
0
source share

Your code is a bit confusing. I do not understand why you are using a POST request to receive data using ajax to populate the select2 field.

Assuming the data returned using the ajax call is in the following format.

  [ { "id": "Some id", "text": "Some text" }, { "id": "ID 2", "text": "Text 2" }, ] 

Now what you can do is pass an extra parameter to your ajax call below

 url: function() { var type = $(this).attr('id'); @if(old('customer')) return '/get' + type + '?customer='+ {{ old('customer') }}; @else return '/get' + type; @endif } 

Now, when your controller returns data, you can add an additional attribute selected:true for the identifier corresponding to this ID.

 if( Request::has('customer') && Request::input('customer') == $id ) { [ "id" => $id, "text" => $text, "selected" => "true" ] } else { [ "id" => $id, "text" => $text, ] } 
0
source share

If I understand correctly, I can recommend you for each of your hidden input select2 box <input type="hidden" name="customer_name" value="{{old('customer_name', '')}}"> where after the event changes for select2 you can insert the selected name (etc. John ). Therefore, if the check fails, you:

 <select id="customer" name="customer" class="searchselect searchselectstyle"> @if(!is_null(old('customer'))) <option value="{{old('customer')}}">{{old('customer_name')}} </option> @endif </select> 
0
source share

You can do something like this:

First, tags are transmitted in the tags, which can be viewed using the pluck utility, as shown below:

 public function create() { $tags= Customer::pluck('name','name'); return view('view',compact('tags')); } 

Then in your form, try the following:

  {!! Form::select('tag_list[]',$tags,old('tag_list'),'multiple','id'=>'tag_list']) !!} 

Remember to call the select2 function.

  $('#tag_list').select2(); 

And finally, in the controller:

 public function store(ArticleRequest $request) { $model = new Model; $tags=$request->input('tag_list'); $model->tag($tags); } 

Note The tag function is not an assistant in Laravel, you implement it! The function takes names and attaches them to an instance of some thing.

Good luck.

0
source share

I think your own decision is pretty much the right one. You say that the list of customers will be very large.

 $customers->where('id', intval(Request::old('customer')))->first() 

Do you need a list stored in the $ customers variable? You can simply find the identifier you need

 App\Customer::where('id', intval(Request::old('customer')))->first() 

Search by identifier should not be ineffective. Otherwise, you can send the name in the form and save it in the old request. Below is some (dirty) javascript.

 $("#form").submit( function() { var sel = document.getElementById("customer"); var text= sel.options[sel.selectedIndex].text; $('<input />').attr('type', 'hidden') .attr('name', "selected_customer_name") .attr('value', text) .appendTo('#form'); return true; }); 

Then, like yvv 16s, answer:

 <option value="{{old('customer')}}">{{old('selected_customer_name')}} 
0
source share

All Articles