datatables, change results from SSI - datatables

i use the SSI-Solution from the datatables-examples.
Now, i want to change and edit some results of the database (for example, i want to change a stored id throug an icon for this id etc.).
For the moment i have no idear at wich point i can catch the results and work with them. Maybe someone can explain it for me.
Here is the code if use for getting the database results
// DB table to use
$table = 'MODUL_1_CONTACTS';
// Table's primary key
$primaryKey = 'ACCOUNT_ID';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array( 'db' => 'CONTACT_GROUP', 'dt' => 0 ),
array( 'db' => 'KD_NO', 'dt' => 1 ),
array( 'db' => 'TYPE', 'dt' => 2 ),
array( 'db' => 'ORG_NAME', 'dt' => 3 ),
array( 'db' => 'VORNAME', 'dt' => 4 ),
array( 'db' => 'NAME', 'dt' => 5 )
);
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP
* server-side, there is no need to edit below this line.
*/
require( $vz.'assets/global/plugins/datatables/ssp.class.php' );
echo json_encode(
SSP::simple( $_GET, $table, $primaryKey, $columns )
);
Here is the JS Code
var table = $('#ajax_table1').DataTable( {
"processing": true,
"serverSide": true,
"ajax": $.fn.dataTable.pipeline( {
url: 'data.php',
pages: 5 // number of pages to cache
} ),
"columnDefs": [
{
"targets": -1,
"data": null,
"defaultContent": "<button class=\"btn yellow-mint uppercase btn-circle\" data-toggle=\"confirmation\" id=\"bs_confirmation_demo_1\">Confirmation 1</button><div class=\"btn-group pull-right\"><button class=\"btn green btn-xs btn-outline dropdown-toggle\" data-toggle=\"dropdown\">Tools<i class=\"fa fa-angle-down\"></i></button><ul class=\"dropdown-menu pull-right\"><li><i class=\"fa fa-trash\"></i> delete </li><li><i class=\"fa fa-file-text\"></i> write letter </li><li><i class=\"fa fa-calendar-plus-ot\"></i> new todo/date </li><li><i class=\"fa fa-file-cubes\"></i> new work </li><li><i class=\"fa fa-print\"></i> Print </li><li><i class=\"fa fa-file-pdf-o\"></i> Save as PDF </li><li><i class=\"fa fa-file-excel-o\"></i> Export to Excel </li></ul></div>"
}],
"language": {
url: '../lang/<?php echo $_GET['lang'].'/'.$_GET['lang']; ?>.json'
},
// setup buttons extentension: http://datatables.net/extensions/buttons/
buttons: [
{ extend: 'print', className: 'btn dark btn-outline' },
{ extend: 'pdf', className: 'btn green btn-outline' },
{ extend: 'csv', className: 'btn purple btn-outline' }
],
"lengthMenu": [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"] // change per page values here
],
//responsive: true,
"bFilter": true,
// set the initial value
"pageLength": 10,
//Layout
"dom": "<'pull-left'f><'pull-right' B>r<'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>><'row'<'col-md-5 col-sm-12'l><'col-md-7 col-sm-12'>>",
} );

Related

How can I create a specific json format based from eloquent Laravel with pivot table relationship?

I'm creating Laravel/Vue SPA and wanted to create a json format like:
{
language: 'Driver',
libs: [{ name: 'Katell Walls' }, { name: 'Isaiah Franks' }]
}, {
language: 'Dumptruck Driver',
libs: [{ name: 'Samuel Goodwin' }]
}, {
language: 'Batching Plant Operator',
libs: [{ name: 'Jermaine Briggs' }]
}, {
language: 'Silo Helper',
libs: [{ name: 'Jurson Jerson' }]
}],
value: []
}
I have 2 tables, and 1 pivot table with many to many relationship. The tables were employees and positions. Then the pivot table is employees_positions.
The employees model has a belongsToMany structure and an attribute that creates full_name:
public function positions()
{
return $this->belongsToMany(Positions::class, 'employees_positions', 'employees_id', 'positions_id')
->withTimestamps();
}
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
I already have the query below which can output $nbcp_emp_positions id and name:
array:4 [▼
0 => array:2 [▼
"libs" => 4
"language" => "Driver"
]
1 => array:2 [▼
"libs" => 8
"language" => "Dumptruck Driver"
]
2 => array:2 [▼
"libs" => 9
"language" => "Batching Plant Operator"
]
3 => array:2 [▼
"libs" => 10
"language" => "Silo Helper"
]
]
How can I query it to get the positions_id from employees_positions and get the full_name values in employees table with having the desired json format above?
Any help is much appreciated.

Call a controller with json data on api plateform

I have build my Application with make:entity,
After I create a query who link all the table to get what I want ( a bit of all tables )
My query is working but now I want to use API Plateform to handling routes.
But I find no way to call my controller with API Plateform notation.
Annotation on Caractéristiques entity.
#[ApiResource(collectionOperations: ['requete' => [
'method' => 'get',
'path' => '/requete',
'controller' => ApiRequeteController::class,
'openapi_context' => [
'summary' => 'get requete',
'requestBody' => [
'content' => [
'application/json' => [
'schema' => [
'type' => 'object',
'properties' =>
[
'montant' => ['type' => 'int'],
'loc' => ['type' => 'string'],
'stat' => ['type' => 'string'],
'type' => ['type' => 'string'],
'sect' => ['type' => 'string'],
],
],
'example' => [
'montant' => 1000000,
'loc' => "test",
'stat' => "test",
'type' => "test",
'sect' => "test",
],
],
],
],
],
],
])]
I have found this way but not working.
give me:
syntax error, unexpected '=>' (T_DOUBLE_ARROW)
on
'method' => 'get',
Any way to do this ?
With POST and another writing
* collectionOperations= {"requete" = {
* "method" = "POST",
* "path" = "/requete",
* "controller" = App\Controller\ApiRequeteController::class,
* "openapi_context" = {
* "summary" = "get requete",
* "requestBody" = {
* "content" = {
* "application/json" = {
* "schema" = {
* "type" = "object",
* "properties" =
* {
* "montant" = {"type" = "int"},
* "loc" = {"type" = "string"},
* "stat" = {"type" = "string"},
* "type" = {"type" = "string"},
* "sect" = {"type" = "string"},
* },
* },
* "example" = {
* "montant" = 1000000,
* "loc" = "test",
* "stat" = "test",
* "type" = "test",
* "sect" = "test",
* },
* },
* },
* },
* }
* }
* }
* )
*/

Laravel 8 - firstOrCreate() doesn't return Default value set in the DB

My MySQL DB has a default value set to 0 for field formed_id:
`former_id` bigint(20) NOT NULL DEFAULT 0
When I use firstOrCreate() method to insert a new record, I do not set formed_id:
$record = Record::firstOrCreate(
[
"name" => "myName",
"nick" => "myNick",
]
);
and the output returns:
{
"id": 10,
"name" => "myName",
"nick => "myNick",
"created_at" => "2020-10-01 00:00:00",
"updated_at" => "2020-10-01 00:00:00",
}
do not contains the former_id field set as default, 0.
To get all fileds in the output model, I need to perform a second query:
$record = Record::firstOrCreate(
[
"name" => "myName",
"nick => "myNick",
]
);
$fullRecord = Record::find($record->id)
in this case the output returns correctly:
{
"id": 10,
"name" => "myName",
"nick => "myNick",
"former_id" => 0,
"created_at" => "2020-10-01 00:00:00",
"updated_at" => "2020-10-01 00:00:00",
}
I do not like this solution because I need to perform two queries instead of one; is there a way to get all fields directly from the firstOrCreate() insert?
Thank you.
Reading the #dave solution:
Laravel 8 - firstOrCreate() doesn't return Default value set in the DB
the final code should be:
$record = Record::firstOrCreate(
[
"name" => "myName",
"nick" => "myNick",
]
);
if ($record->wasRecentlyCreated) {
$record->refresh();
}
This is indeed correct behaviour. It could be highly inefficient by default to fetch a model directly after it has been created.
In your case you could add an $attributes property to your model to achieve default properties and prevent having to do another query.
/**
* The model's attributes.
*
* #var array
*/
protected $attributes = [
'former_id' => 0,
];

SOLVED How to display datatables by using id as the keyword data that is displayed (filter data from controller)

So I have Table A which has ['id', 'data', 'data']
Table B has ['id', 'id_A', 'data', 'data']
I want to display it in the datatable with the source of table B where the data displayed is based on id_A
data id send from controller Table A
public function dataTable()
{
$data = Kabupaten::query();
return DataTables::of($data)
->addColumn('action', function ($data) {
return view('layouts._action', [
'data' => $data,
]);
})
->addColumn('kabkota', function ($data) {
return ''.$data->kabkota.'';
})
->addIndexColumn()
->rawColumns(['action','kabkota'])
->make(true);
}
my route
Route::resource('/kabupaten', 'KabupatenController');
Route::get('/data/kabupaten', 'KabupatenController#dataTable')->name('data.kabupaten');
Route::post('/kabupaten/import_excel', 'KabupatenController#import_excel');
Route::resource('/satuan', 'SatuanController');
Route::get('data/satuan', 'SatuanController#dataTable')->name('data.satuan');
Route::post('/satuan/import_excel', 'SatuanController#import_excel');
Route::get('/kab', 'HomeController#kabupaten');
Route::get('/sat/{id}', 'HomeController#satuanTable');
Route::get('/home/kab', 'HomeController#dataTable')->name('home.kab');
Route::get('/home/satuan/', 'HomeController#satuanTable')->name('home.satuan');
script
<script>
var table = $('#dataTable').DataTable( {
columnDefs: [
{ width: 20, targets: [0]},
{ width: 90, targets: [6]},
{ width: 75, targets: [3,1]},
{ width: 125, targets: [2,5] },
],
responsive: true,
processing: true,
serverSide: true,
searching: true,
ordering: false,
"ajax": "{{ route('home.satuan') }}",
"columns": [
{data: 'DT_RowIndex', name: 'id'},
{data: 'npsn', name: 'npsn'},
{data: 'nama', name: 'nama'},
{data: 'jenis', name: 'jenis'},
{data: 'alamat', name: 'alamat'},
{data: 'kabkota', name: 'kabkota'},
{data: 'capaian', name: 'capaian'},
]
});
</script>
trying to get id
public function satuanTable(Request $request)
{
$id = $request();
$data = Satuan::query()->where('id_kabkota', '=', $id);
return DataTables::of($data)
->addIndexColumn()
->rawColumns(['kabkota'])
->make(true);
}
I hope someone can help me to solve this,, thankyou and im sorry for the language,
Edit
i want displaying all data from table B , where id_fruit like id in TABLE A.
Like this
the table
SOLVED
Send id to controller view
->addColumn('link', function ($data) {
return ''.$data->data.'';
})
passing id to view
return view('guest.view')->with(['id_' => $id]);
Send back using ajax
"ajax":"{{ url('guest/data') }}" + '/' + "{{ $id }}",

Datatables custom filtering with server side

I'm using DataTables and also using server side processing (Django).
I have a seperate textfield in which I use it to custom filter data in the DataTable after the table has been rendered already.
The following works just fine (I want to custom filter columns):
var table = $('#problem_history').DataTable( {
"bJQueryUI": true,
"aaSorting": [[ 1, "desc" ]],
"aoColumns": [
// various columns here
],
"processing": true,
"serverSide": true,
"ajax": {
"url": "/getdata",
"data": {
"friend_name": 'Robert'
}
}
} );
So on the page load (initial load of the DataTable) it filters for 'Robert' just fine. But now I want to programmatically change the data to filter for "friend_name" == "Sara"
I already tried the following, the filteredData has a correct filtered object but the table itself does not redraw with the new filter.
var filteredData = table.column( 4 ).data().filter(
function ( value, index ) {
return value == 'Sara' ? true : false;
}
);
table.draw();
I also tried this but no luck:
filteredData.draw();
How can I achieve this?
Thank you for your help.
Here is a very nice explanation on how to do it:
https://datatables.net/reference/option/ajax.data
I am currently using this code:
"ajax": {"url":"/someURL/Backend",
"data": function ( d ) {
return $.extend( {}, d, {
"parameterName": $('#fieldIDName').val(),
"parameterName2": $('#fieldIDName2').val()
} );
}
}
You call it by doing the following:
$('#myselectid').change(function (e) {
table.draw();
});
If you want to submit by clicking on the button, change the .change to .click and make sure that ID is pointing to button's id in a HTML
You've almost got it. You just need to assign the filter var to
the data parameter that's passed in the datatables request:
"ajax": {
"url": "/getdata",
"data": {
"friend_name": $('#myselectid').val();
}
}
And to filter the data, just call draw() on the select change event
$('#myselectid').change(function (e) {
table.fnDraw();
});
For Basic searches, you should use the search() API:
// Invoke basic search for 'a'
dt.search('a', false)
For more complex queries, you can utilize searchBuilder backend by intercepting the ajax call through an open API. Here are some searchBuilder examples:
// Basic example:
// . (searchable_fields contains 'a'
// AND (office = Tokyo AND Salary > 100000)
// )
$('#problem_history').on('preXhr.dt', function(e, settings, data){
data['searchBuilder'] = {
'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["Tokyo"], 'value1': "Tokyo"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [100000], 'value1': 100000
}
]
,'logic': 'AND'
}
})
// Complex example:
// . (searchable_fields contains 'a'
// AND (
// (office = Tokyo AND Salary > 100000)
// OR (office = London AND Salary > 200000)
// )
// )
$('#problem_history').on('preXhr.dt', function(e, settings, data){
data['searchBuilder'] = {
'criteria': [
{'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["Tokyo"], 'value1': "Tokyo"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [100000], 'value1': 100000
}
]
,'logic': 'AND'
}
,{'criteria': [
{'data': 'Office', 'origData': 'office', 'type': 'string'
,'condition': '='
,'value': ["London"], 'value1': "London"
}
,{'data': 'Salary', 'origData': 'salary', 'type': 'num'
,'condition': '>'
,'value': [200000], 'value1': 200000
}
]
,'logic': 'AND'
}
]
,'logic': 'OR'
}
})
SearchBuilder Logic Types:
=
!=
contains
starts
ends
<
<=
>
>=
between
null
!null
SearchBuilder data value blocks:
value: [<val>] seems to always equal value1
value2: For upper bounds of 'between' logic where value1 would be lower bounds