namespace Cubist\Backpack\Http\Controllers;
use Cubist\Backpack\Http\Controllers\Base\XSendFileController;
+use Cubist\Backpack\Magic\Fields\SelectFromArray;
+use Cubist\Util\Text;
use Illuminate\Support\Facades\Auth;
class CubistSelect2Controller
if (!can('edition')) {
return response(null)->setStatusCode('403');
}
- $data = json_decode(storage_path('select2/' . $hash . '.json'));
- $res = [];
+
+ $perPage = 10;
+ $data = json_decode(file_get_contents(storage_path('select2/' . $hash . '.json')), true);
+ $term = request()->get('q', null);
+ $page = request()->get('page', 1);
+ $offset = ($page - 1) * $perPage;
+ if (null === $term) {
+ $sub = $data;
+ } else {
+ $search = SelectFromArray::normalize($term);
+ $sub = [];
+ foreach ($data as $k => $v) {
+ if (strpos($v['n'], $search) !== false) {
+ $sub[$k] = $v;
+ }
+ }
+ }
+ $sub = array_slice($sub, $offset, $perPage, true);
+ $results = [];
+ foreach ($sub as $k => $v) {
+ $results[] = ['id' => $k, 'text' => $v['t']];
+ }
+
+ $res = ['results' => $results, 'pagination' => ['more' => count($sub) == $perPage]];
return response()->json($res);
}
+
+
}
use Cubist\Backpack\CubistBackpackServiceProvider;
+use Cubist\Util\Text;
class SelectFromArray extends Field
{
$this->setAttribute('allows_null', false);
}
if ($this->getAttribute('ajax', false)) {
- $results = [];
+ $data = [];
foreach ($this->getOptions() as $k => $v) {
- $results[] = ['id' => $k, 'text' => $v];
+ $data[$k] = ['t' => $v, 'n' => self::normalize($v)];
}
- $data = ['results' => $results, 'pagination' => ['more' => false]];
$hash = hash('sha256', print_r($data, true));
$name = $hash . '.json';
$dir = \Cubist\Util\Files\Files::mkdir(storage_path('select2'));
{
return $this->getColumnData()['options'];
}
+
+ public static function normalize($str)
+ {
+ $str = trim($str);
+ $str = mb_strtolower($str);
+ return Text::removeAccents($str);
+ }
}
function initUntriggeredSelectFromArray() {
// trigger select2 for each untriggered select2 box
- $('.select2_from_array').each(function (i, obj) {
+ $('.select2_from_array:not(.select2-hidden-accessible)').each(function (i, obj) {
if ($(obj).closest('.item.sample').length > 0) {
return;
}
var options = {
theme: "bootstrap"
};
-
if ($(this).is('[data-ajax]')) {
options.ajax = {
- url: '{{backpack_url('select2')}}' +'/'+ $(this).data('ajax'),
- dataType: 'json'
+ url: '{{backpack_url('select2')}}' + '/' + $(this).data('ajax'),
+ dataType: 'json',
+ delay: 500,
};
}
-
- if (!$(obj).hasClass("select2-hidden-accessible")) {
- $(obj).select2(options);
- }
+ $(obj).addClass('init').select2(options);
});
}
});