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
Related
I am creating column headers from the rows of a mysql table (Button1) and it works fine. eg: I get headers |A|B|C| in the grid when I query the table for the rows A, B, C.
Button2 queries the same table to get different rows eg D, E. Both queries return expected data.
But, the new header data from Button2 is appended to the column headers created from Button1. ie I get |A|B|C|D|E|.
What I want is just the headers |D|E|. How can I clear the old column headers and replace with the new?
Thanks for any help.
var ColModel = []
var availabilitydept = ''
$("#button1").click(function() {
availabilitydept = 'de85768424332'
set_up_avgrid()
});
$("#button2").click(function() {
availabilitydept = 'de56827997021'
set_up_avgrid()
});
function set_up_avgrid()
{
$("#avgrid").jqGrid("GridUnload")
$('#avgrid').jqGrid('clearGridData');
create_colmodel()
create_grid()
}
function create_colmodel()
{
ColModel.push({name :'Date',index: 'dateindex',resizable : false, align:'left',
frozen : true, width : 80, search: false,
resizable : false});
$.ajax
({
url: 'tl2_get_rooms_by_dept.php',
type: 'GET',
async: false, // ** it don't work with async true.
data: 'userid=' + 'TL2-0001'
+ '&deptid=' + availabilitydept,
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
ColModel.push({name: row.roomname, index: row.roomname + i, align:'center', resizable : false, width:50, search:false});
}
}
});
}
function create_grid()
{
$("#avgrid").jqGrid(
{
shrinkToFit: false,
height : 200,
width : 290,
colModel: ColModel,
});
}
Solved: I'm sure there are better ways but what I ended up doing was to change my query to select all rows from the mysql table, then create the grid. Of course the grid then had a column for each row in the table. To get rid of the unwanted columns I composed a function to loop through the column names and hide/show as required using.
$"#avgrid").jqGrid('hideCol',[row.roomname]);
$("#avgrid").jqGrid('showCol',[row.roomname]);
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
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.
Hi is there any way to pass detailRow reference to a function using kendo grid template column?
Here is my trail.
function detailInit(e) {
detailRow = e.detailRow;
detailRow.find("#mygrid").kendoGrid({
dataSource: {
data: empModel,
},
columns: [
{
field: "empId",
title: "Emp ID",
template: '<a href="\\#" onclick="showEmpDetails(\'#= detailRow #\')"> }
]
});
});
Try to place every detailRow you retrieve at the detailInit into globally located array, then pass this index to your click method (or some sort of key - could be dictionary, rows has uid) and then make the method to read the row details from your array/collection based on the id you have passed in. (Ideally read the row details directly from your datasource by the uid, no need to duplicate the data.) Please refer to below code as pseudo code, I didn't have a chance to run it.
var rows = new Array();
$('.clickable').click(function () {
// get the id for your detail
var detailId = this.attr('detailId');
// pass it further
showEmpDetails(detailId);
});
function detailInit(e) {
detailRow = e.detailRow;
// add roe to your (cache) collection
rows[rows.legth] = detailRow ;
detailRow.find("#mygrid").kendoGrid({
dataSource: {data: empModel},
columns: [
{
field: "empId",
title: "Emp ID",
// add attribute onto your a tag
template: '<a href="\\#" detailId = "#= rows.legth #" class="clickable">'
}
]
});
});
function showEmpDetails(id) {
// read from your collection and do what you need
console.log(rows[id]);
}
I have a grid which uses a remote store and remote pagination because I have too many records.The store for the main grid is:
Ext.define('ArD.store.RecordsListStore', {
extend: 'Ext.data.Store',
model: 'ArD.model.RecordsListModel',
autoLoad: true,
autoSync: true,
remoteSort: true,
remoteFilter: true,
pageSize: 15,
proxy: {
type: 'ajax',
actionMethods: 'POST',
api: {
read: g_settings.baseUrl + 'index.php/recordslist/getAll',
destroy: g_settings.baseUrl + 'index.php/recordslist/deleteRecord'
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount',
successProperty: 'success'
},
writer: {
root: 'data',
writeAllFields: true,
encode: true
}
}
});
then I populate my grid and and it's all fine. But the problem is that I have a combobox which looks like this:
{
xtype: 'combo',
id: 'records_list_form_id',
emptyText: 'Choose Form',
editable: false,
store: 'FilterRecordsByForm',
displayField: 'title',
valueField: 'id',
lastQuery: '',
triggerAction: 'all',
queryMode: 'remote',
typeAhead: false,
width: 200,
listeners: {
select: this._filterRecords
}
}
And when I select something from the combobox there's the function :
_filterRecords: function()
{
var recStore = Ext.getStore('RecordsListStore');
var a = Ext.getCmp('records_list_form_id').getValue( );
var rec = Ext.getStore('FilterRecordsByForm').getAt(a);
console.log(recStore);
},
mostly just trying some things but I can get the ID of the selected element from the combobox and that is where I am.
What I need is having the id to make a new query usign my AJAX api (PHP/SQL backend) and populate the grid with the info related with this id. In my case I have 1:M relations so when I pass the Id i expect M records which I want to render on the place of the old grid.
Thanks
Leron
Use filter() method. Provide information that you need to filter by and store object will automatically request updated info from the server (you already have remoteFilter configured).
Look at Ext.Ajax() to make an on-demand ajax call to the server-side to load up your data and then use Store.loadData() or something like that to re-populate the Grid.