How to use java script variable inside blade syntax. (getting error Use of undefined constant buttonID)
The below is the code :
var t = $("#datatable").DataTable({
"order": [[ 1, 'asc' ]],
"ajax": "questions1/get-data",
"deferRender": true,
"processing": true,
sAjaxDataProp: "",
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "description" },
{ "data": "answers.[, ].name" },
{ "data": "campaigns.[, ].name" },
{ "data": "label" },
{
sortable: false,
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
return '#can('view', $question)<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>#endcan
#can('update', $question)<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>#endcan';
}
}
],
});
Use the code below:
"render": function ( data, type, full, meta ) {
var buttonID = full.id;
#can('view', $question)
return '<span class="glyphicon glyphicon-eye-open" aria-hidden="true"/>';
#endcan
#can('update', $question)
return '<span class="glyphicon glyphicon-pencil" aria-hidden="true"/>';
#endcan
}
Related
I have a table of orders,
filtering, sorting and records per page is done via server side.
How can i make the filtering of the status with the checkbox (see attached screenshot) work?
When changing entries number or searching in searchbox or sorting the action that retrieve the data is triggered (GetList()) , i want to trigger it when check\Uncheck one of the checkbox status.
My Action :
public ActionResult GetList()
{
//Server Side parameters
int start = Convert.ToInt32(Request.Form["start"].FirstOrDefault());
int length = Convert.ToInt32(Request.Form["length"].FirstOrDefault());
string searchValue = Request.Form["search[value]"].FirstOrDefault();
string sortColumnName = Request.Form["columns["+Request.Form["order[0][column]"]+"][name]"].FirstOrDefault();
string sortDirection = Request.Form["order[0][dir]"].FirstOrDefault();
List<Order> orderList = new List<Order>();
orderList = _unitOfWork.Order.GetAll().ToList();
int totalRows = orderList.Count;
foreach (Order order in orderList)
{
order.StringDate = order.UsDate.Day + "/" + order.UsDate.Month + "/" + order.UsDate.Year;
}
//
//filtering done here
//
int totalRowsAfterFiltering = orderList.Count;
//
//Sorting done here
//
//orderList = orderList.OrderBy(x => x.Id //sortColumnName + " " + sortDirection).ToList<Order>();
orderList = orderList.Skip(start).Take(length).ToList<Order>();
foreach (Order order in orderList)
{
order.AllowComplaint = allowComplaint(order.Id.ToString());
}
return Json(new { data = orderList, draw = Request.Form["draw"], recordsTotal = totalRows ,
recordsFiltered = totalRowsAfterFiltering});
}
Javascript\Ajax call the Action :
<script>
$(document).ready(function () {
$('#tblData').DataTable({
"ajax": {
"url": "OrderAdmin/GetList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "id", "name": "Id" },
{ "data": "orderStatus", "name": "OrderStatus" },
{ "data": "productName", "name": "ProductName" },
{ "data": "stringDate", "name": "StringDate" },
{ "data": "userNameToShow", "name": "UserNameToShow" },
{ "data": "storeName", "name": "StoreName" },
{
"data": "quantity", "name": "Quantity", "render": function (data) {
if (data > 1)
return `<div class="text-center" style="font-weight:bold;background-color:darkseagreen"><label >${data}</label></div>`
else
return `<div class="text-center"><label>${data}</label></div>`
}
},
{ "data": "cost", "name": "Cost" },
{
"data": "fullAddress", "name": "FullAddress", "render": function (data) {
return `<textarea readonly>${data}</textarea>`
},
"width": "20%"
},
{ "data": "trackingNumber", "name": "TrackingNumber", "width": "200px"},
{
"data": {
"orderStatus": "orderStatus",
"id": "id",
"allowComplaint": "allowComplaint"
},
"render": function (data) {
if (data.orderStatus == 'Accepted') {
return `
<div class="text-center">
<a href="/Admin/OrderAdmin/UpdateOrder/${data.id}" class="btn btn-success text-white" style="cursor:pointer">
<i class="fas fa-edit"></i>
</a>
</div>
`}
else if (data.orderStatus == 'Done' && data.allowComplaint) {
return `
<div class="text-center">
<a href="/Admin/Complaints/AddComplaint/${data.id}" class="btn btn-info text-white" style="cursor:pointer">
<i class="fas fa-ticket-alt"></i>
</a>
</div>
`
}
else { return `<div></div>` }
}, "width": "5%"
}
],
"serverSide": "true",
"order": [0, "desc"],
"processing": "true"
});
});
</script>
I am working on an ASP.Net Core 2.1 MVC web application and I am using DataTables.Net datatable v1.10.19 for my lists.
I am creating master/detail drill downs where the first list (DataTable) of job activity provides a link on each row to the respective detail record. I am using pagination as well.
On the detail record, I want to have a breadcrumb that takes me back to the job activity list, and to the correct page number where I was at then I clicked on the detail link.
What I am doing is passing the query properties I am using on the Job Activity DataTable as query string parameters to the detail page so I can correctly populate the breadcrumb URL back to the job activity page.
I can see on the DataTable.Net API reference that I can use page.info() from the API to get the current page using something like this;
var table = $('#example').DataTable();
var info = table.page.info();
$('#tableInfo').html(
'Currently showing page '+(info.page+1)+' of '+info.pages+' pages.'
);
The problem is that I initialize the DataTable as part of the table setup and in the body of that function is where I am populating the link data for the detail page. I can't seem to do two .DataTable() calls, such as doing the call to the DataTable function to get the page info to initialize a pageNumber variable and then call the main .DataTable function as it causes the init of the main DataTable function to fail.
So, I need a way to get the current page from within the main .Datatable() function, if possible.
Here is my main DataTable() function;
jQuery(document).ready(function($) {
//Get the Timezone offset between local time and UTC
var d = new Date();
var m = d.getTimezoneOffset();
var minutesToOffset = parseInt(m, 10);
var companyId = $('#company-filter').val();
var siteId = $('#site-filter').val();
var aging = $('#aging-filter').val();
console.log(`companyId: [${companyId}], siteId: [${siteId}], Aging Days: [${aging}]`);
var table = $("#ssflist").DataTable({
//"dom": "lrtip",
"initComplete": function() {
$('#spinner1').hide();
$('#spinner2').hide();
},
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"order": [[6, "desc"]],
"ajax": {
"url": `/JobActivity/LoadData?companyId=${companyId}&siteId=${siteId}&agingDays=${aging}`,
"type": "POST",
"datatype": "json"
},
"oLanguage": {
"sSearch": "Filter"
},
"columnDefs": [
{ "orderable": false, "targets": [9, 10] },
{ "className": "text-center", "targets": [0, 9, 10] },
{
"targets": [6, 7],
"render": function(data) {
if (data != null) {
return moment(data).subtract(minutesToOffset, 'minutes').format('M/D/YYYY h:mm a');
}
}
}
],
"columns": [
{
"render": function(data, type, full, meta) {
if (full.ManifestStatus === 0) {
return '<i class="far fa-clock text-primary" title="Not started"></i>';
} else if (full.ManifestStatus === 1) {
return '<i class="fas fa-sync-alt text-primary" title="Pending"></i>';
} else if (full.ManifestStatus === 2) {
return '<i class="far fa-file-alt text-primary" title="Manifested"></i>';
} else if (full.ManifestStatus === 3) {
return '<i class="far fa-times-circle text-danger" title="Failed"></i>';
} else if (full.ManifestStatus === 4) {
return '<i class="far fa-check-circle text-primary" title="Uploaded"></i>';
} else return '<i class="far fa-question-circle text-primary" title="Unknown status"></i>';
},
"name": "ManifestStatus"
},
{
"render": function(data, type, full, meta) {
if (type === 'display' && data != null) {
data =
`<a href="/shippingServicesFileDetail/detail?id=${full.Id
}&returnTitle=Job Activity List&companyId=${companyId}&siteId=${siteId}&agingDays=${
aging}">
<button type="button" class="btn btn-outline-primary btn-sm">` +
data +
`</button></a>`;
}
return data;
},
"data": "Id",
"name": "Id"
},
{ "data": "TransactionId", "name": "TransactionId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "ReferenceId", "name": "ReferenceId", "autoWidth": true, "defaultContent": "" },
{ "data": "CreatedDate", "name": "CreatedDate", "autoWidth": true, "defaultContent": "" },
{ "data": "UploadDate", "name": "UploadDate", "autoWidth": true, "defaultContent": "" },
{ "data": "Environment", "name": "Environment", "autoWidth": true, "defaultContent": "" },
{
"render": function(data, type, full, meta) {
data = full.H1RecordCount + full.D1RecordCount + full.C1RecordCount;
return data;
},
"name": "Count"
},
{
"render": function(data, type, full, meta) {
if (full.AzureFileUrl != null) {
data =
`<a href="/JobActivity/getManifest?azureFileUrl=${full.AzureFileUrl
}&azureFileName=${full.AzureFileName}">
<i class="far fa-arrow-alt-circle-down text-primary" title="Download Manifest"></a>`;
return data;
} else {
return null;
}
},
"name": "AzureFileUrl"
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback":
function(settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
},
});
$('#companyId').on('change',
function() {
table.search(this.text).draw();
});
});
The relevant link code is...
data = `<a href="/shippingServicesFileDetail/detail?id=${full.Id
}&returnTitle=Job Activity
List&companyId=${companyId}&siteId=${siteId}&agingDays=${
aging}">
I want to add a parameter to this link that represents the current page of the Datatable so that I can pass it back in the breadcrumb link on the detail page and have the datatable go to the correct page.
So I need a way to get the current page from within the
var table = $("#ssflist").DataTable({
function itself so I can pass that value in the link to the detail page.
Is there a property or method from within the Datatable function that will get me the current page value?
I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );
You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/
It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.
I'm using JQuery DataTable with server side processing. And I've written this code:
public List<VacationRequest> GetVacationRequestsWithProfiles(int displayStart, int displayLength, out int allDataCount, out int filteredDatacount, string searchParam = "", string searchDir = "")
{
....
switch(searchDir)
{
case "asc":
requests = requests.OrderBy(x => x.FirstName).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
case "desc":
requests = requests.OrderByDescending(x => x.FirstName).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
default:
requests = requests.OrderBy(x=>x.VacationRequestState).ThenByDescending(x=>x.DateEnd).Skip(displayStart).Take(displayLength);
break;
}
....
}
The problem: I need to get default (empty) search parameter to this method, when page loaded. How I may resolve this?
This is a part of JS code:
"aoColumns": [
{ "data": "ID", "visible": false, bSortable: false, bSearchable: false },
{ "data": "Name" },
{
"data": "VacationRequestStatus",
bSortable: false,
bSearchable: false,
"mRender": function (data, type, full) {
return '<div class = "' + data + '"> <span class="glyphicon glyphicon-question-sign requested-img"></span> <span class="glyphicon glyphicon-ok accept-img"> </span> <span class="glyphicon glyphicon-remove decline-img"></span> </div>';
}
},
{ "mData": "Position", bSortable: false, bSearchable: false },
{ "mData": "DateStart", bSortable: false, bSearchable: false },
{ "mData": "DateEnd", bSortable: false, bSearchable: false },
{
bSortable: false,
bSearchable: false,
data: null,
className: "center",
defaultContent: '<button class="btn btn-danger decline-button">Decline</button> <button class="btn btn-primary accept-button">Accept</button>'
}
]
because dont know where u put ajax try add this command ine the line before aoColumns
"destroy" : true,
"aoColumns": [
thats command to stop data display in datable but after search data will diplay hope solve ur problems
I am newbie for DataTables. I want to add button on each row for edit and delete(like below image)
I have tried with code:
Test.cfm
<table id="myDataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>UserID</th>
<th>Name</th>
<th>UserName</th>
<th>Passowrd</th>
<th>Email</th>
<th>IsActive</th>
<th>Command</th>
</tr>
</thead>
<tbody>
</tbody>
$(document).ready(function () {
var oTable = $('#myDataTable').dataTable({
// "bServerSide": true,
"sAjaxSource": "fetchUserData.cfm",
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mData": null },
{ "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
{ "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
{ "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%" },
{ "mData": "Email","sTitle": "Email" , "sWidth": "20%"},
{ "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
{
"mData": null,
"bSortable": false,
"mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
}
]
});
} );
fetchUserData.cfm
{
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
[
"2",
"arun singh",
"arun",
"arun",
"arunsingh#test.com",
"0",
""
],
[
"9",
"s s",
"sam3",
"sam3",
"ss#s.com",
"0",
""
],
[
"10",
"sameek mishra",
"sam56",
"sam",
"same#s.com",
"0",
""
],
[
"11",
"narendra kumar",
"narendra",
"nav",
"sa#sa.com",
"1",
""
],
[
"12",
"test test",
"test",
"test",
"test2#test.com",
"1",
""
]
]
}
Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:
fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]
dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered.
I just hardcoded this info to your data. You should get the right values from counts in your server sided script.
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
If you have the column names already set in the html part, you don't need to add sTitle.
The mRender Function takes three parameters:
data = The data for this cell, as defined in mData
type = The datatype (can be ignored mostly)
full = The full data array for this row.
So your mRender function should look like this:
"mRender": function(data, type, full) {
return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
}
Find a working Plunker here
var table =$('#example').DataTable( {
data: yourdata ,
columns: [
{ data: "id" },
{ data: "name" },
{ data: "parent" },
{ data: "date" },
{data: "id" , render : function ( data, type, row, meta ) {
return type === 'display' ?
'</i>' :
data;
}},
],
}
}
take a look here... this was very helpfull to me
https://datatables.net/examples/ajax/null_data_source.html
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
I contribute with my settings for buttons: view, edit and delete.
The last column has data: null
At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.
//...
columns: [
{ title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
{ title: "Id", "data": "id", defaultContent: '', "visible":false },
{ title: "Nombre", "data": "nombre" },
{ title: "Apellido", "data": "apellido" },
{ title: "Documento", "data": "tipo_documento.siglas" },
{ title: "Numero", "data": "numero_documento" },
{ title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
{ title: "Teléfono", "data": "telefono1" },
{ title: "Email", "data": "email1" }
, { title: "", "data": null }
],
columnDefs: [
{
"searchable": false,
"orderable": false,
"targets": 0
},
{
width: '3%',
targets: 0 //la primer columna tendra una anchura del 20% de la tabla
},
{
targets: -1, //-1 es la ultima columna y 0 la primera
data: null,
defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button> <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
},
{ orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
],
//...
enter image description here
Take a Look.
$(document).ready(function () {
$('#datatable').DataTable({
columns: [
{ 'data': 'ID' },
{ 'data': 'AuthorName' },
{ 'data': 'TotalBook' },
{ 'data': 'DateofBirth' },
{ 'data': 'OccupationEN' },
{ 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
],
bServerSide: true,
sAjaxSource: 'EmployeeDataHandler.ashx'
});
});
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
well, i just added button in data.
For Example,
i should code like this:
$(target).DataTable().row.add(message).draw()
And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!