Ad

How To Provide A Datasource For Select2 With October CMS Via The Built In Ajax Framework

October CMS provides an extensive AJAX framework, that I'm looking to use to populate a Select2 box with.

According to Select2, using a remote dataset happens as follows:

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      params.page = params.page || 1;
      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatRepo, 
  templateSelection: formatRepoSelection 
});

But from the October CMS docs, I cannot figure out how to pass the data to the server manually.

Questions are: which URL to use, and which parameters do I need to pass along so that October knows which function I want to access. Also, how can I capture the result without a partial being loaded?

This might be a trivial question; I might be looking in the wrong direction. Maybe the AJAX framework should not be used at all. Any insights on the correct way to proceed?

** EDIT FOLLOWING CORRECT ANSWER BY SAMUEL **

To make Select2 work with a remote dataset in combination with October CMS, please take into account the following pitfalls. Below is my working code:

// SELECT 2
$('select').select2({
    /*placeholder: "Your placeholder", // Remove this, this causes issues*/
    ajax: {
        // Use transport function instead of URL as suggested by Samuel
        transport: function(params, success, failure) {
            var $request = $.request('onSelect', {
                data: params.data
            });
            $request.done(success);
            $request.fail(failure);
            return $request
        },
        dataType: 'json',
        delay: 250,
        data: function (params) {
            console.log(params);
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data,params) {
            console.log(data);
            return {
                // The JSON needs to be parsed before Select2 knows what to do with it.
                results: JSON.parse(data.result)
            };
        },
        cache: true
    },
    minimumInputLength: 1
});

Below is the example output I used in combination with this Select2 example:

[  
   {  
      "id":1,
      "text":"Henry Kissinger"
   },
   {  
      "id":2,
      "text":"Ricardo Montalban"
   }
]

Above JSON was generated by my VisitorForm.php file:

<?php namespace XXX\VisitorRegistration\Components;

use Cms\Classes\ComponentBase;
use XXX\VisitorRegistration\Models\Visitor;
use October\Rain\Auth\Models\User;

class VisitorForm extends ComponentBase {
    public function componentDetails()
    {
        return [
            'name' => 'Visitor Form',
            'description' => 'Description of the component'
        ];
    }

    // The function that returns the JSON, needs to be made dynamic
    public function onSelect() {
        return json_encode(array(array('id'=>1,'text'=>'Henry Kissinger'), array('id'=>2,'text'=>'Ricardo Montalban')));
    }
}

Voilà, hope this can be useful.

Ad

Answer

Pass the transport option instead of url. Here is an example:

$(".js-data-example-ajax").select2({
    ajax: {
        transport: function(params, success, failure) {

            /*
             * This is where the AJAX framework is used
             */
            var $request = $.request('onGetSomething', {
                data: params.data
            })

            $request.done(success)
            $request.fail(failure)

            return $request
        },

        dataType: 'json'
    },
    // ...
});
Ad
source: stackoverflow.com
Ad