Fix support for custom Select2 options via the AJAX framework (#4414)

Fixes #4413. Credit to @DanHarrin
This commit is contained in:
Dan Harrin 2019-07-01 16:04:15 +01:00 committed by Luke Towers
parent 3eac21219f
commit 7f29cbe13c
3 changed files with 37 additions and 2 deletions

View File

@ -68,11 +68,28 @@ Use the `data-handler` attribute to source the select options from an AJAX handl
data-minimum-input-length="2"
data-ajax--delay="300"
data-request-data="foo: 'bar'"
></select>
></select>
```
The AJAX handler should return results as an array.
```php
public function onGetOptions()
{
$results = [
[
'id' => 1,
'text' => 'Foobar',
],
...
];
return ['result' => $results];
}
```
Due to the fact that JavaScript reorders numeric keys when interpreting the JSON data received by the AJAX handler, we suggest the method above for defining `results`. Support for the original `results` array format is however retained to ensure backwards compatibility.
```php
public function onGetOptions()
{

View File

@ -86,7 +86,25 @@
return $request
},
processResults: function (data, params) {
var results = data.result;
var options = [];
for (var i in results) {
if (results.hasOwnProperty(i)) {
var isObject = i != null && i.constructor.name === 'Object';
options.push({
id: isObject ? results[i].id : i,
text: isObject ? results[i].text : results[i],
});
};
};
return {
results: options,
};
},
dataType: 'json'
}
}

View File

@ -3493,7 +3493,7 @@ if($element.hasClass('select-hide-selected')){extraOptions.dropdownCssClass+=' s
var source=$element.data('handler');if(source){extraOptions.ajax={transport:function(params,success,failure){var $request=$element.request(source,{data:params.data})
$request.done(success)
$request.fail(failure)
return $request},dataType:'json'}}
return $request},processResults:function(data,params){var results=data.result;var options=[];for(var i in results){if(results.hasOwnProperty(i)){var isObject=i!=null&&i.constructor.name==='Object';options.push({id:isObject?results[i].id:i,text:isObject?results[i].text:results[i],});};};return{results:options,};},dataType:'json'}}
var separators=$element.data('token-separators')
if(separators){extraOptions.tags=true
extraOptions.tokenSeparators=separators.split('|')