laravel-datatables-html
laravel-datatables-html copied to clipboard
Select2:make, DT not rendered
Hi @yajra , i make a simple DT with editor with simple Select extending Datatables Service;
Select::make('id_carrier')->label(Lang::get('validation.attributes.id_carrier'))->fieldInfo('')->multiEditable(false) ->tableOptions('carrier','name','id_carrier', function(\Illuminate\Database\Query\Builder $query) { $query->where('deleted', 0)->where('active', 1); }, 'prestashop'), Very nice. Now, i want use Select2:make instaed Select with ajax value call.
Select2::make('id_carrier')->label(Lang::get('validation.attributes.id_carrier'))->fieldInfo('test')->multiEditable(false)
->opts(
[
'theme' => 'bootstrap4',
'ajax' => [
'url' => route('api.carriers.search'),
'type' => 'GET',
'dataType' => 'json',
'delay' => 250,
]
]
)
The Output of url
{"results":[{"id_carrier":37,"name":"UPS"},{"id_carrier":39,"name":"MBE"},{"id_carrier":72,"name":"Fedex"}]}
But DT is not rendered.
This is the code for JsonResponse for DT Ajax Call
/**
* Build DataTable class.
*
* @param mixed $query Results from query() method.
* @return DataTableAbstract
*/
public function dataTable($query)
{
return datatables()
->eloquent($query)
->setRowId('id_order_carrier')
}
The output
-npm i select2 -put window.select2 = require('select2'); into app.js before datatables requires -npm run dev for mixing .
What is missing?
You need to follow the select2 ajax response requirements. JSON structure is
'results' => [
['id' => 1, 'text' => 'text']
],
'pagination' => [
'more' => true
]
Here is a basic resource that I uses if you like:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Select2JsonResource extends JsonResource
{
protected $text = 'text';
protected $id = 'id';
/**
* Set keys to be used for KVP result.
*
* @param string $text
* @param string $id
* @return $this
*/
public function usingKeys($text, $id)
{
$this->text = $text;
$this->id = $id;
return $this;
}
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
self::withoutWrapping();
$data = $this->resource->map(function ($data) {
return [
'id' => $data[$this->id],
'text' => $data[$this->text],
];
});
return [
'results' => $data,
'pagination' => [
'more' => (bool) $this->resource->nextPageUrl(),
],
];
}
}
Usage
$paginator = User::query()->orderBy('first_name')->paginate(request('limit', 10));
return Select2JsonResource::make($paginator)->usingKeys('name', 'id');
Hi , my Select2 FIeld is paginate very well. But when i open EDIT mode select2 is not filled!! Why?
I read want initValue. How can I use it?
Make sure your ajax can return an initialValue that is triggered when you do an Edit mode.
This issue is stale because it has been open for 30 days with no activity.
This issue was closed because it has been inactive for 7 days since being marked as stale.