Yajra data tables order by column - laravel

I'm using yajra/laravel-datatables plugin to get create datatables in laravel. This is my code.
$data = MyModel::latest()
->where('subject', 3)
->get();
return Datatables::of($data)->make(true);
This is my js code
var table = $('#empTable').DataTable({
processing: true,
serverSide: true,
serverMethod: 'post',
ajax: "{{ url('my url') }}",
columns: [
{data: 'reference_no', name: 'reference_no'}
]
});
But unfortunately data is not sorted and I'm not getting latest data first ('id' 'desc'). It would be a great help if someone has a solution

You can overwrite the default sorting from dataTable in order to achieve the desired result:
var table = $('#empTable').DataTable({
processing: true,
serverSide: true,
serverMethod: 'post',
order: [],
ajax: "{{ url('my url') }}",
columns: [
{data: 'reference_no', name: 'reference_no'}
]
});
By default dataTable will sort the table by the first column, so the reference_no in your case, but since you are providing the inital ordering from your data, you can set the default ordering to an empty array.

Related

Dynamic value of columns Datatable

i create datatable, i want create dynamically columns data.
my init datatable looks like this :
var columnsData = [
{data: 'name'},
{data: 'phone'}
];
var dtable = $('#dtable').DataTable({
serverSide : true,
ajax : '/data',
columns : columnsData,
});
in some condition, make columns data changed. i don't have solution for that.
example columns what i want to change :
columnsData = [
{data: 'name'},
{data: 'address'}
]
i was try
dtable.columns.data( columnsData ).load();
dtable.columns.data( columnsData ).draw();
but still doesn't work.
You can use the below function to recreate the data table with changes in structure.
function getDT() {
$.ajax({
url: '/data',
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter(columnNames[i])});
}
$('#dtable').DataTable( {
processing: true,
serverSide: true,
ajax: '/data',
columns: columns
} );
}
});
}
please find the complete implementation on Example

Redraw datatables with search

I am using DataTables. I have added the below code when the page is loading and the table getting all data as expected.
var table = $('#expensesTable').DataTable({
responsive: true,
searchDelay: 500,
processing: true,
serverSide: true,
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
},
columns: [
{data: 'expense_id'},
{data: 'expense_date'},
{data: 'expense_description'},
{data: 'expense_amount'},
{data: 'vendor_name'},
],
});
Now, I have added a date range picker where it will search data in the server and response will be given back to query via Ajax.
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
var start = picker.startDate.format('YYYY-MM-DD');
var end = picker.endDate.format('YYYY-MM-DD');
jQuery.ajax({
type: "POST",
url: '/books/daybooks/datatable',
data: {start : start, end : end},
success: function(data)
{
console.log(data);
} // Success End
}); //AJAX End
});
Now i am getting all expected filter data as success, but now I need to redraw the table with newly got data after the filter of Ajax call.
if i use $('#expensesTable').DataTable().draw(); then it will do draw without filter,
So i can draw table with filter data?
Thanks in advance.
Instead of introducing a new ajax call (the jQuery ajax), you can re-use your existing DataTables ajax call when submitting your date range filter data.
To do this, you need to take the following steps:
(1) Update your DataTables ajax option:
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
data: function () {
return { "start": start, "end" end };
}
},
This data function allows you to dynamically assign values to your request. They will be added as standard URL-encoded form data, in the usual way for POST requests.
See here for more information. There are several different ways to use ajax.data. For example, if you were using serverSide processing (which you are not) then the above approach would not work correctly.
(2) To re-use your DataTables ajax call, you can use this:
table.ajax.reload();
See here for more information.
This replaces your jQuery ajax call:
var start;
var end;
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
start = picker.startDate.format('YYYY-MM-DD');
end = picker.endDate.format('YYYY-MM-DD');
table.ajax.reload();
});
When the table first loads (not using reload()), the filter values will be null.

How to create a datatable with Yajra in a show laravel view?

I have the related models Request 1: M Tasks and I would like to show a datatable with yajra in the show view of the requests, that is to say that if I enter the show view of the request with id = 1 it will show me a datatable filled only with the tasks related to the request id = 1, I tried to return the datatable from the show function of the controller but I didn't know how to only get the tasks related to the request.
In any case, I don't know if this is of any use, but, this is how I make my datatable for the index of the tasks:
public function taskData()
{
$tasks = Task::join('requests', 'requests.id', '=', 'tasks.request_id')
->select('tasks.id', 'requests.code_request', 'tasks.fake_id',
'tasks.date');
return Datatables::of($tasks)
->addColumn('btn', 'tasks.actions')
->rawColumns(['btn'])
->make(true);
}
and then in my view:
<script>
$(function() {
$(document).ready(function(){
// initializing Datatable
var table = $("#tareas-table").DataTable({
serverSide: true,
pageLength: 10,
ajax: '{!! route('datatables.tareas') !!}',
columns: [
{ data: 'fake_id', name: 'tareas.fake_id' },
{ data: 'codigo_solicitud', name: 'solicituds.codigo_solicitud' },
{ data: 'fecha_inicio', name: 'tareas.fecha_inicio' },
{ data: 'estado', name: 'tareas.estado' },
{ data: 'btn', name: 'btn',orderable:false,serachable:false,sClass:'text-center' }
]
});
});
</script>
thanks
You can use the DataTableScopeContract for that.
The docs have an example for that: https://datatables.yajrabox.com/services/scope

jqGrid: function $("#gridView").jqGrid("getGridParam", "data") return null?

I had a problem with jqGrid
When i use:
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
height:350,
rownumbers:true,
treeGrid: true,
treeGridModel : 'adjacency',
ExpandColumn : 'id',
ExpandColClick: true
....
$("#gridView").jqGrid("getGridParam", "data") return array
$("#gridView").jqGrid({
url:"grid.php",
colModel:[
{ name: 'id', index:'id'},
],
datatype: "json",
mtype:"post",
pager:"#pager",
rowNum:50,
rowList:[10,50,100,500,1000],
viewrecords:true,
height:350,
rownumbers:true,
....
$("#gridView").jqGrid("getGridParam", "data") return null ??
I've read article here JQGrid getGridParam not returning ID of data item
But I cannot set loadonce:true because of my dynamic data for each click
You don't need to use loadonce: true in case of treeGrid: true. jqGrid fills internal parameters data and _index for treegrid automatically (see the part of the code).
I suppose that you get null as the value of data parameter because you try to access data before the data will be loaded from the server. Try to use $(this).jqGrid("getGridParam", "data") inside of loadComplete callback. The callback will be called after filling of data.

jqGrid without using ajax

I want to display data in jqGrid without using ajax. I have data in Json array format. The data in the array is
not getting displayed. It prints only the column names. PFB the code
$("#myTable").jqGrid({
data: [ 'Jack', '1000' ] ,
datatype: "json",
colNames:['User Name','Series No'],
colModel:[
{name:'User Name',width:55},
{name:'Series No', width:90}
],
viewrecords: true,
caption:"JSON Example"
});
Am I missing anything? Please help

Resources