Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 not loading data

I recently upgraded to Rails 5.2 and ruby 2.5.1 and my select box stopped working.

I had to change requiere file in my admin.jsand add the full version to even view the select box

//= require select2-full

but now the ajax query to get the data or even the initial selection is not displaying any results. I am using Gon to pass data to my js and I have checked that gon has the correct values. My js.coffee is as follows:

clientFormatResult = (client) ->
  client.email

clientFormatSelection = (client) ->
  client.email

$ ->
  $select_input = $('#publish_to')
  $select_input.val(' ')
  $select_input.select2({
    width: '420px'
    height: 'auto'
    placeholder: "Search"
    minimumInputLength: 2
    multiple:true
    closeOnSelect: true
    tokenSeparators:[',',' ']
    ajax: {
      url: $select_input.data('search-endpoint')
      data: (term, page) ->
        {
          q: term # search term
          page_limit: 10
        }
      results: (data, page) -> # parse the results into the format expected by Select2.
        console.log("result")
      # since we are using custom formatting functions we do not need to alter remote JSON data
        results: data.manage_clients
      }
    initSelection: (element, callback) ->
      callback(gon.published_to)
    formatResult: clientFormatResult
    formatSelection: clientFormatSelection
  })

My controller search endpoint:

def search
    clients = Client.where("email like '%#{params[:q]}%'").map { |c| { :id => c.id, :email => c.email } }
    render :json => clients
  end

private
  def client_params
    params.require(:client).permit(:email, :password, :password_confirmation, :first_name, :last_name, :organisation, :assigned_team)
  end

search-endpoint result:

{
"manage_clients": [
{
"id": 46,
"email": "[email protected]"
},
{
"id": 365,
"email": "[email protected]"
}
]
}

Extract of the view source code where the select input is:

<div class="input string required publish_to">
<label class="string required control-label" for="report_clients">
Publish to
</label>
<input data-search-endpoint="/my-endpoint-search" id="publish_to" name="publish_to" type="hidden" value="" multiple="" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"><span class="select2 select2-container select2-container--default" dir="ltr" style="width: 420px;"><span class="selection"><span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1"><ul class="select2-selection__rendered"><li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="Search for a client" style="width: 418px;"></li></ul></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span>
<div>
<a class="add_button button" href="/some_url">Action</a>
</div>
</div>

I have tried the solution suggested here of chenging the controller respond_to but no change. I also tried adding a dataType: 'json' to the ajax call as suggested here Adding .select2('val',[]) at the end of the first select2 I tried manually adding { id: '1', text:'example' } to the initSelection I am not getting any error in the console

But the ajax call doesn't seem to be working. In the console there are no calls to the search-endpoint.

like image 350
marimaf Avatar asked Sep 25 '26 17:09

marimaf


1 Answers

The problem was that I was using select2 4.0 and the code was designed for 3.5

I had to change my input to a select, and add there a multiple="multiple" attribute instead of declaring it as part of the select2 options. That was the main change to make it work. After that a few tweaks I had to change the initSelection formatter and change the ajax results from results to processResults. The final code is this:

%select#publish_to{ :name => 'publish_to', :multiple => 'multiple', :type => 'hidden', "data-lookup-endpoint" => my_endpoint_path }

And the coffeescript:

formatValues = (values) ->
  data = []
  i = 0
  while i < values.length
    data.push
      id: values[i].id
      text: values[i].email
    i++
  data

$ ->
  $select_input = $('#publish_to')
  $select_input.val('')
  $select_input.select2({
    placeholder: 'Search for a Client'
    width: '420px'
    height: 'auto'
    data: formatValues(gon.published_to)
    allowClear: true
    minimumInputLength: 2
    tokenSeparators:[',',' ']
    ajax: {
      url: $select_input.data('lookup-endpoint')
      dataType: 'json'
      data: (term, page) ->
        {
          q: term # search term
        }
      processResults: (data, page) -> # parse the results into the format expected by Select2.
      # since we are using custom formatting functions we do not need to alter remote JSON data
        results: formatValues(data.manage_clients)
      }
  })
  # To set initial values:
  $('#publish_to').val(getIds(gon.published_to)).trigger 'change'

controller, changed the param from [:q] to [:q][:term]:

def search
    clients = Client.where("email like '%#{params[:q][:term]}%'").map { |c| { :id => c.id, :email => c.email } }
    render :json => clients
  end
like image 141
marimaf Avatar answered Sep 27 '26 11:09

marimaf