how to check status in if condition - javascript

I want to check the status which is come from a model in the form 0 and 1 but I have to show 0 as a enable and 1 as a disable but don't know how to use if below code
#push('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#role-table').DataTable({
serverSide: true,
processing: true,
responsive: true,
ajax: '{{ route("admin.role.getRoleList") }}',
columns: [
{ data: 'id', name: 'id',className:'text-center' },
{ data: 'name', name: 'name' },
{ data: 'status', name: 'status' },
{ data: 'action', name: 'action', classrole: 'text-center', orderable: false }
],
stateSave: true
});
});
</script>
#endpush

For formatting your status column, use this:
{
data: 'status',
name: 'status',
render: function ( data, type, row ) {
return data?$'<span> disable </span>':'<span> enable </span>';
}
}
Note that you have the power to use HTML tags for formatting your data columns.
For more information visit DataTable Renders

Write your yajra datatables query like this:
return datatables()->of($model)
->editColumn('status', function ($query) {
if($query->status == 0)
{
return 'enable';
}
else
{
return 'disable';
}
})
->escapeColumns([])
->make(true);

Related

How Link to Route in JS

I'm using Laravel 8.
I wish I could link the field "nama" to show the categories in detail (the examples in red arrows).
JS for table
#push('scripts')
<script>
$(function() {
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
</script>
#endpush
I also wish to know how to set the date format because when I looked at that field it feels so messed up. Here's my view table.
Try this
$(function() {
$('#kategoris-table').DataTable({
processing: true,
serverSide: true,
ajax: 'kategori/json',
columns: [
{ data: 'id', name: 'id' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/category_details/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
});
You can read here more about it - https://datatables.net/reference/option/columns.createdCell

How to set cutom template for kendo grid columns

I need to set Kendo grid action button Icon based on value. My code as follows,
function InitProductServicesGrid() {
var prodServiceDataSource = new kendo.data.DataSource({
transport: {
type: "json",
read:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/GetProductServiceDetailsList",
type: "POST",
contentType: 'application/json',
data: GetAdditonalData,
datatype: "json"
},
update:
{
url: SERVER_PATH + "/LTSService/ProductsService.asmx/SaveProductService",
type: "POST",
contentType: 'application/json',
datatype: "json"
}
},
schema: {
data: function (result) {
return JSON.parse(result.d);
},
model: {
id: "Id",
fields: {
Id: { type: "int" },
ServiceTime: { type: "string" },
IsActive: { type: "boolean"}
}
}
},
requestEnd: function (e) {
if (e.type === "destroy") {
var grid = $("#productServicesGrid").data("kendoGrid");
grid.dataSource.read();
}
},
error: function (e) {
e.preventDefault();
if (e.xhr !== undefined && e.xhr !== null) {
var messageBody = e.xhr.responseJSON.Message;
ShowGritterMessage("Errors", messageBody, false, '../App_Themes/Default/LtsImages/errorMessageIcon_large.png');
var grid = $("#productServicesGrid").data("kendoGrid");
grid.cancelChanges();
}
},
pageSize: 20,
});
$("#productServicesGrid").kendoGrid({
dataSource: prodServiceDataSource,
sortable: true,
filterable: false,
pageable: true,
dataBound: gridDataBound,
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "Id", title: "", hidden: true },
{
field: "ServiceTime",
title: "Time Standard",
sortable: false,
editor: function (container, options) {
var serviceTimeTxtBox = RenderServiceTime();
$(serviceTimeTxtBox).appendTo(container);
},
headerTemplate: '<a class="k-link" href="#" title="Time Standard">Time Standard</a>'
},
{
title: "Action", command: [
{
name: "hideRow",
click: hideRow,
template: comandTemplate
}
],
width: "150px"
}
]
});
}
I wrote a custom template function as follows,
function comandTemplate(model) {
if (model.IsActive == true) {
return '<a title="Hide" class="k-grid-hideRow k-button"><span class="k-icon k-i-lock"></span></a><a title="Hide"></a>';
}
else {
return '<a title="Show" class="k-grid-hideRow k-button"><span class="k-icon k-i-unlock"></span></a><a title="Show"></a>';
}
}
But when I debug the I saw the following value for model value.
I followed this sample code as well. here you can see, I also set the custom template like the sample code. Please help me to solve this. Why I can't access model IsActive value from comandTemplate function.
Updated
When clicking hideRow action, I access the dataItem as follows.
function hideRow(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
if (dataItem.IsActive == true) {
dataItem.IsActive = false;
}
else {
dataItem.IsActive = true;
}
}
Is there any possible way to access data from template function as above or any other way?
I would suggest a different approach because you can't access grid data while rendering and populating grid.
My suggestion is to use two actions and hide it based on the flag (in your case IsActive).
Something like this: Custom command
NOTE: in visible function you can access item!
EDIT: you can access it and change it on dataBound traversing through all data.
Check this example: Data bound
I don't see the advantage of relying on the grid commands. You can render any button you want yourself and and use the dataBound event to bind a click handler:
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{
template: function(dataItem) {
const isActive = dataItem.isActive;
return `<a title=${isActive ? "Hide": "Show"} class="k-grid-hideRow k-button"><span class="k-icon k-i-${isActive ? 'lock' : 'unlock'}"></span></a>`
}
}
],
dataBound: function(e) {
e.sender.tbody.find(".k-grid-hideRow").click(evt => {
const row = evt.target.closest("tr")
const dataItem = e.sender.dataItem(row)
dataItem.set("isActive", !dataItem.isActive)
})
},
dataSource: [{ name: "Jane Doe", isActive: false }, { name: "Jane Doe", isActive: true }]
});
Runnable Dojo: https://dojo.telerik.com/#GaloisGirl/eTiyeCiJ

How do I make search input in kendo grid?

I am a new Software Developer. In my new company, I use their framework to code. And its using Kendo. I tried to make a search field for Kendo Grid so I can find a specific information in that grid. I tried this method but it doesn't work. Honestly, I don't understand how to use 'transport' things. I call an API to get datas for my grid and I call it in my grid's line of code.
{
type: 'panel',
fields: [{
type: 'panel',
text: 'Payment List',
name: 'payment',
fields: [{
type: 'grid',
name: 'paymentGrid',
data: [],
toolbar: function () {
return `<div class="toolbar" style="width:370px">
<label class="search-label" for="search-reservation" style="color:white"> Cari berdasarkan No. Pesanan: </label>
<input type="search" id="search-reservation" class="search-class">
</div>`
},
sourceOptions: {
pageSize: 10
},
options: {
selectable: true,
autoheight: true,
allowCopy: true,
altrows: true,
pageable: {
refresh: true,
buttonCount: 5,
pageSizes: [10, 20, 50, 100]
},
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
}
},
url: function (option) {
var arg = option.data
$.ajax({
method: 'POST',
url: APILink,
data: JSON.stringify(arg),
dataType: 'json',
contentType: 'application/json',
}).done(function (resp) {
if (resp.data != null) {
var nameMap = [];
$.each(resp.data, function (key, val) {
nameMap.push({
id: val.id,
supplier: val.supplier,
reservation_id: val.reservation_id,
currentPayment: val.state
});
});
option.success({
data: nameArray,
total: resp.total
});
}
}).fail(function (jqXHR, status, err) {
option.error(err);
});
},
fields: [{
name: 'number',
text: 'No. ',
template: "#= ++record #",
width: 70,
}, {
name: 'supplier',
text: 'Supplier',
}, {
name: 'reservation_id',
text: 'No. Reservation',
}, {
name: 'currentPayment',
text: 'status',
}, {
name: 'checked',
text: 'choose',
width: 100,
template: function (item) {
return !!item.checked
? `<input id="${item.id}" name='ceklis-boks[]' class="check" checked value="${item.id}" type=\'checkbox\' />`
: `<input id="${item.id}" name='ceklis-boks[]' class="check" value="${item.id}" type=\'checkbox\' />`
}
}],
onDataBound: 'dataBound',
}]
}
Then I used the same code as I mention before in previous link, and replace the ID (#) in that code with mine. But, it won't work. I come to his fiddle and I thought it was because his PlainDs variable and $("#category").kendoAutoComplete({...}) or serverPaging, serverSorting, or serverFiltering. So, I comment all of it here and still working properly. So basically, I can just write the code from line 49 - 81 like in his post. But why it doesn't work? For your information, I call the grid with its name or sometimes I give it a class. But it won't work. Is it a problem if I use class or name instead of ID?
The term "Not working" is too broad here, if you can be more specific on what is not working, we may be able to pinpoint better. However I assume you know how to get the grid to display and so on. so basically to get the search to work I usually have this in the click event of my "Search" button:
var grid = $("#myGrid").data("kendoGrid");
var ds = grid.dataSource;
var searchVal = $("#search-reservation").val();
if ( searchVal ) {
ds.filter({
field: "reservation_id", operator: "eq", value: searchVal
});
}
else {
ds.filter({});
}

Boolean 1 and 0 not searchable on yajra laravel-datatables

I have this boolean data of 1 = 'Active' and 0 = 'Inactive'.
I successfully rendered it to the datatable, but the problem if I trying to search 'Active' or 'Inactive' it shows No matching records found.
Is there any solution for this problem?
Here is my datatable js code
columns: [
{ data: 'photo', name: 'photo' },
{ data: 'full_name', name: 'full_name' },
{ data: 'm_lname', name: 'm_lname'},
{ data: 'm_fname', name: 'm_fname'},
{ data: 'm_mname', name: 'm_mname'},
{ data: 'm_gender', name: 'm_gender' },
{ data: 'm_datebaptized', name: 'm_datebaptized' },
{ data: 'm_isactive', name: 'm_isactive',
render: function ( data, type, full, meta ) {
return data ? "Active" : "Inactive" ;
}
},
{ data: 'action', name: 'action' },
],columnDefs: [
{ targets: [2,3,4], visible: false},
{ targets: '_all', visible: true },
{ searchable: true, targets: '_all'},
{ searchable: false, targets: [0,8]},
{ orderData: 2, targets: 1 },
],
Thank you.
try to move mapping to
return datatables()->of(User::all()->map(function ($item) {
$item->m_isactive = $item->m_isactive ? 'Active' : 'Inactive';
return $item;
})->toJson();
and delete
render: function ( data, type, full, meta ) {
return data ? "Active" : "Inactive" ;
}

Datatables: You clicked on undefined's row

I have this definition of a Datatable defined on a Thymeleaf template of a SpringBoot application, using Datatables:
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function() {
var table = $('#workerEventTable').DataTable( {
order: [[ 0, "desc" ]],
select: true,
bLengthChange: false,
stateSave: true,
pageLength: 20,
ajax: 'http://127.0.0.1:1234/acerinox/api/deviceevent/datatableList',
"columns": [
{ data: 'id' },
{ data: 'deviceId' },
{ data: 'companyName' },
{ data: 'description' },
{ data: 'battery' },
{ data: 'dateTime' },
{ data: 'signal' },
{ data: 'data' },
{ data: 'alarm' }
]
});
setInterval( function () {
table.ajax.reload( null, false ); // user paging is not reset on reload
}, 1000 );
table.on('select.dt deselect.dt', function() {
localStorage.setItem( 'DataTables_selected', table.rows( { selected: true }).toArray() )
})
$('#workerEventTable tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data[0]+'\'s row' );
} );
} );
/*]]>*/
</script>
Expecting that when I click on a row I should see the ID, but instead I see this error message: Datatables: You clicked on undefined's row
You are using object based data because you defined columns.data. To access the id try this:
alert( 'You clicked on '+data.id+'\'s row' );

Categories