SmartAdmin DataTables - how to import ajax data from component.ts - ajax

I am using the SmartAdmin Angular 5 template to render a DataTable. The SmartAdmin datatable example, which I have modified to be LoginHistory, gets its ajax data from a JSON file stored in the web app, as I show below. This works fine. But, how can I modify it to get its data from a string defined in component.ts?
loginhistory.component.html
<div id="content">
<div class="row">
<sa-big-breadcrumbs [items]="['Table', 'Data Tables']" icon="table"
class="col-xs-12 col-sm-7 col-md-7 col-lg-4"></sa-big-breadcrumbs>
</div>
<sa-widgets-grid>
<div class="row">
<article class="col-sm-12">
<div sa-widget [editbutton]="false" color="blueDark">
<header>
<span class="widget-icon"> <i class="fa fa-table"></i> </span>
<h2>Export to PDF / Excel</h2>
</header>
<div>
<div class="widget-body no-padding">
<sa-datatable
[options]="{
ajax: '../../assets/api/tables/datatables.standard.json', // <<<<<<< HOW TO USE loginHistoryData FROM loginhistory.component.ts????
columns: [
{data: 'id'},
{data: 'name'},
{data: 'phone'},
{data: 'company'},
{data: 'zip'},
{data: 'city'},
{data: 'date'}
],
buttons: [
'copy', 'excel', 'pdf', 'print'
]
}"
tableClass="table table-striped table-bordered table-hover"
>
<thead>
<tr>
<th data-hide="mobile-p">ID</th>
<th data-class="expand">Name</th>
<th>Phone</th>
<th data-hide="mobile-p">Company</th>
<th data-hide="mobile-p,tablet-p">Zip</th>
<th data-hide="mobile-p,tablet-p">City</th>
<th data-hide="mobile-p,tablet-p">Date</th>
</tr>
</thead>
</sa-datatable>
</div>
</div>
</div>
</article>
</div>
</sa-widgets-grid>
</div>
loginhistory.component.ts
import { Component, OnInit } from '#angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
#FadeInTop()
#Component({
selector: 'sa-datatables-case',
templateUrl: './loginhistory.component.html',
})
export class LoginHistoryComponent implements OnInit {
public loginHistoryData: any;
constructor() {}
ngOnInit() {
this.loginHistoryData =
+ '{'
+ ' "data": ['
+ ' {'
+ ' "id": "1",'
+ ' "name": "Jennifer",'
+ ' "phone": "1-342-463-8341",'
+ ' "company": "Et Rutrum Non Associates",'
+ ' "zip": "35728",'
+ ' "city": "Fogo",'
+ ' "date": "03/04/14"'
+ ' },'
+ ' {'
+ ' "id": "2",'
+ ' "name": "Clark",'
+ ' "phone": "1-516-859-1120",'
+ ' "company": "Nam Ac Inc.",'
+ ' "zip": "7162",'
+ ' "city": "Machelen",'
+ ' "date": "03/23/13"'
+ ' },'
+ ' ]'
+ '}';
}
}

A little trial & error solved the problem. Just needed to change the ajax label to data, and include the name of the component.ts parameter.
I also cleaned up the loginHistoryData parameter by using the typescript nomenclature instead of a string.
loginhistory.component.html
<div id="content">
<div class="row">
<sa-big-breadcrumbs [items]="['Table', 'Data Tables']" icon="table"
class="col-xs-12 col-sm-7 col-md-7 col-lg-4"></sa-big-breadcrumbs>
</div>
<sa-widgets-grid>
<div class="row">
<article class="col-sm-12">
<div sa-widget [editbutton]="false" color="blueDark">
<header>
<span class="widget-icon"> <i class="fa fa-table"></i> </span>
<h2>Export to PDF / Excel</h2>
</header>
<div>
<div class="widget-body no-padding">
<sa-datatable
[options]="{
data: loginHistoryData, //<<<< change ajax to data and add the name of the component.ts parameter
columns: [
{data: 'id'},
{data: 'name'},
{data: 'phone'},
{data: 'company'},
{data: 'zip'},
{data: 'city'},
{data: 'date'}
],
buttons: [
'copy', 'excel', 'pdf', 'print'
]
}"
tableClass="table table-striped table-bordered table-hover"
>
<thead>
<tr>
<th data-hide="mobile-p">ID</th>
<th data-class="expand">Name</th>
<th>Phone</th>
<th data-hide="mobile-p">Company</th>
<th data-hide="mobile-p,tablet-p">Zip</th>
<th data-hide="mobile-p,tablet-p">City</th>
<th data-hide="mobile-p,tablet-p">Date</th>
</tr>
</thead>
</sa-datatable>
</div>
</div>
</div>
</article>
</div>
</sa-widgets-grid>
</div>
loginhistory.component.ts
import { Component, OnInit } from '#angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
#FadeInTop()
#Component({
selector: 'sa-datatables-case',
templateUrl: './loginhistory.component.html',
})
export class LoginHistoryComponent implements OnInit {
public loginHistoryData: any;
constructor() {}
ngOnInit() {
this.loginHistoryData = [
{
"id": "1",
"name": "Jennifer",
"phone": "1-342-463-8341",
"company": "Et Rutrum Non Associates",
"zip": "35728",
"city": "Fogo",
"date": "03/04/14"
},
{
"id": "2",
"name": "Clark",
"phone": "1-516-859-1120",
"company": "Nam Ac Inc.",
"zip": "7162",
"city": "Machelen",
"date": "03/23/13"
}
];
}
}

Related

Ajax filter column datatable

I'd want to display result by column dropdown filter. But after choose table doesn't update result.
My main goal is filter by "Компания" column and that selector must be on top of the table.
`
$(document).ready(function() {
var exampleDataTable = $('#example').DataTable({
responsive: true,
colReorder: true,
dom: 'Bfrtip',
buttons: [
{
extend: 'excel',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
language: {
buttons: {
colvis: 'Отображение столбцов'
},
"processing": "Подождите...",
"search": "Поиск:",
"lengthMenu": " _MENU_ ",
"info": "Показано с _START_ до _END_ записей из _TOTAL_",
"infoEmpty": "Записи с 0 до 0 из 0 записей",
"infoFiltered": "(отфильтровано из _MAX_ записей)",
"infoPostFix": "",
"loadingRecords": "Загрузка записей...",
"zeroRecords": "Записи отсутствуют.",
"emptyTable": "В таблице отсутствуют данные",
"paginate": {
"first": "Первая",
"previous": "<",
"next": ">",
"last": "Последняя"
},
"aria": {
"sortAscending": ": активировать для сортировки столбца по возрастанию",
"sortDescending": ": активировать для сортировки столбца по убыванию"
}
},
"iDisplayLength": 10,
"aLengthMenu": [[ 3, 10, 20, 50, 100 ,-1],[ 3, 10,20,50,100,"все"]],
stateSave: true,
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$(nRow).attr('id', aData[0]);
},
'serverSide': 'true',
'processing': 'true',
'paging': 'true',
'order': [],
'ajax': {
'url': 'fetch_data.php',
'type': 'post',
'data': {
from_attr_1_l: from_attr_1_l,
from_attr_2_l: from_attr_2_l
},
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
} }); });
`
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-md-8">
<table id="example" class="table">
<thead>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Номер</th>
<th>ФИО</th>
<th>Дата</th>
<th>Срок</th>
<th>Кол-во мест</th>
<th>Метка</th>
<th>ИНН</th>
<th>Телефон</th>
<th>КПП</th>
<th>Компания</th>
<th>Адрес</th>
<th>Email</th>
<th>Ответственный</th>
<th>Партнер</th>
<th>К. телефон</th>
<th>К. email</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
I used different solutions also from https://datatables.net/examples/api/multi_filter_select.html and https://datatables.net/forums/discussion/73081/select-dropdown-list-filter but didn't work.

Laravel + Vue V-IF updating in the database but not in the view

I have a project when I'm using Laravel 7.3 + Vue.
I am trying to assign a company to an internal employee. When I click the "Assign Company" button everything is fine and I can select the company in a select box, but when I click the "Save Company" button now, I can see the change in my database, but I don not see the changes live in my view/template, I need to refresh the webpage to see the assigned company.
This is my File.vue between the <template>:
<td><h4 v-if="editEmpleado" class="text-black-50">{{EmpleadosInterno.empresa}}</h4>
<select v-else class="form-control" id="Cliente" v-model="ClienteSeleccionado">
<option v-for="Cliente in Clientes"
:key="Cliente.id"
:value="Cliente">{{Cliente.nombreempresa}}</option>
</select>
</td>
<td>
<a v-if="editEmpleado" type="button" class="btn btn-primary" v-on:click="onClickEdit()">
Assign Company
</a>
<button v-else type="button" class="btn btn-success" v-on:click="onClickUpdate()">
Save Company
</button>
</td>
And this is my script
export default {
props: ['EmpleadosInterno'],
data() {
return {
ClienteSeleccionado: {},
Clientes: [],
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
editEmpleado: true
}
},
mounted() {
axios.get('/Clientes').then((response) => {
this.Clientes = response.data;
},
);
},
methods: {
onClickEdit() {
this.editEmpleado = false;
},
onClickUpdate() {
const params = {
nombreempresa: this.ClienteSeleccionado.nombreempresa
}
axios.put(`/EmpleadosInternos/${this.EmpleadosInterno.id}`, params).then((response) => {
const EmpleadosInterno = response.data;
this.$emit('update', EmpleadosInterno);
this.editEmpleado = true;
});
},
This is my services.vue
<div class="container">
<div class="row justify-content-center text-center">
<div class="col-md-12">
<h2 class="text-primary">Empleados Registrados:</h2>
<table class="table table-bordred table-striped ">
<thead>
<tr>
<th>Nombre</th>
<th>Telefono</th>
<th>Empresa</th>
<th>Acción</th>
</tr>
</thead>
<tbody>
<empleadocomponente-component
v-for="(EmpleadosInterno, index) in EmpleadosInternos"
:key="EmpleadosInterno.id"
:EmpleadosInterno="EmpleadosInterno"
#update="updateEmpleadosInterno(index, ...arguments)"
#delete="deleteEmpleadosInterno(index)">
</empleadocomponente-component>
</tbody>
</table>
</div>
</div>
</div>
<script>
export default {
data(){
return {
EmpleadosInternos: [],
}
},
mounted() {
axios.get('/EmpleadosInternos').then((response) => {
this.EmpleadosInternos = response.data;
},
);
},
methods: {
updateEmpleadosInterno(index, EmpleadosInterno){
this.EmpleadosInternos[index] = EmpleadosInterno;
},
deleteEmpleadosInterno(index){
this.EmpleadosInternos.splice(index, 1);
}
}
}
</script>

How to create a modal for rows in a table using Bootstrap 4

I am creating a table in an html file. The table is populated with data from a json file using ajax call. I am using datatable in bootstrap for loading data from json file. https://datatables.net/extensions/responsive/examples/initialisation/ajax.html.
Now I want to open a modal on clicking a row in the table. The model part is not working. Also, I want to populate the modal with the data from the corresponding row. Can anyone please help me
The table part in table.html file is below:
<div class="table-responsive">
<table class="table table-bordered responsive" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Email</th>
<th>Phone no</th>
<th>Start date</th>
</tr>
</thead>
</table>
</div>
The ajax call in demo.js file
// Call the dataTables jQuery plugin
$(document).ready(function() {
$("#dataTable").DataTable({
ajax: "./data/newusers.json",
columns: [
{ data: "name" },
{ data: "location" },
{ data: "email" },
{ data: "phone" },
{ data: "startdate" }
]
});
});
The json file is below:
{
"data": [
{
"name": "Tiger Nixon",
"location": "Bangalore",
"email": "tiger.nixon#yahoo.com",
"phone": "7896546789",
"startdate": "2018/04/25"
},
{
"name": "Garrett Winters",
"location": "Goa",
"email": "garrett.wint34#gmail.com",
"phone": "6398764532",
"startdate": "2018/07/25"
}
]
}
I tried this based on https://datatables.net/extensions/responsive/examples/display-types/bootstrap-modal.html
// Call the dataTables jQuery plugin
$(document).ready(function() {
$("#dataTable").DataTable({
ajax: "./data/newusers.json",
columns: [
{ data: "name" },
{ data: "location" },
{ data: "email" },
{ data: "phone" },
{ data: "startdate" }
],
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function(row) {
var data = row.data();
return "Details for " + data[0];
}
}),
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: "table"
})
}
}
});
});
The above code is not working. Can anyone please help me?
If you want to use ajax data with the DataTables responsive details modal display option, the "trick" is to add an extra empty column with class="none" for the modal trigger...
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Email</th>
<th>Phone no</th>
<th>Start date</th>
<th class="none"></th>
</tr>
</thead>
and then use the column type and target option to make clicking the tr row trigger the modal...
responsive: {
details: {
type: 'column',
target: 'tr',
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details for ' + data.name;
}
}),
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table'
})
}
},...
Demo of responsive details modal
Alternately, you can use a Bootstrap modal in the markup and its show.bs.modal event to populate the modal with data as needed using jQuery. The from the row render method can be passed using data attributes to the modal. With this method you have complete control over the modal content.
HTML:
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 id="modalTitle"></h3>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</div>
</div>
JS:
"columns": [
...
{ "data": "fieldname", "render": function(data, type, row) {return '<button class="btn btn-primary" data-toggle="modal" data-id="'+row.id+'" data-title="'+row.title+'" data-target="#myModal">'+data+'</button>'} },
...
],
$("#myModal").on('show.bs.modal', function (e) {
var triggerLink = $(e.relatedTarget);
var id = triggerLink.data("id");
var title = triggerLink.data("title");
$("#modalTitle").text(title);
$(this).find(".modal-body").html("<h5>id: "+id+"</h5>");
});
Demo of custom Bootstrap modal

Datatables Handlebars Use of undefined constant

I am working on a a page to display a datatables with row details. I have used exactly the info on the website as follow:
#extends('layouts.app')
#section('style')
<!-- CSS -->
<!-- Select2 -->
<link href="{{ asset('/plugins/select2/select2.min.css') }}" rel="stylesheet" type="text/css" />
<!-- DataTables -->
<link rel="stylesheet" href="{{ asset('/plugins/datatables/dataTables.bootstrap.css') }}">
#stop
#section('scriptsrc')
<!-- JS -->
<!-- Select2 -->
<script src="{{ asset('/plugins/select2/select2.full.min.js') }}" type="text/javascript"></script>
<!-- DataTables -->
<script src="{{ asset('/plugins/datatables/jquery.dataTables.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/dataTables.bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('/plugins/datatables/handlebars.js') }}"></script>
#stop
#section('content')
<!-- table widget -->
<div class="box box-info">
<div class="box-header">
<i class="fa fa-cloud-download"></i>
<h3 class="box-title">Employee List</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div><!-- /.box-tools -->
</div>
<div class="box-body">
<table id="employeeTable" class="display table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Manager name</th>
<th>Name</th>
<th>Manager ID</th>
<th>Is Manager</th>
<th>Region</th>
<th>Country</th>
<th>Domain</th>
<th>Subdomain</th>
<th>Management Code</th>
<th>Job role</th>
<th>Type</th>
</tr>
</thead>
</table>
<script id="details-template" type="text/x-handlebars-template">
<table class="extra_info display table-bordered table-hover" cellspacing="0" width="50%">
<tr>
<td>Full name:</td>
<td>{{ name }}</td>
</tr>
</table>
</script>
</div>
</div>
#stop
#section('script')
<script>
$(document).ready(function() {
var employeeTable;
var template = Handlebars.compile($("#details-template").html());
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
employeeTable = $('#employeeTable').DataTable({
serverSide: true,
processing: true,
ajax: {
url: "{!! route('ajaxlistemployee') !!}",
type: "POST"
},
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'employee.id'},
{ data: 'manager_name', name: 'manager.name'},
{ data: 'name', name: 'employee.name'},
{ data: 'manager_id', name: 'employee.manager_id'},
{ data: 'is_manager', name: 'employee.is_manager'},
{ data: 'region', name: 'employee.region'},
{ data: 'country', name: 'employee.country'},
{ data: 'domain', name: 'employee.domain'},
{ data: 'subdomain', name: 'employee.subdomain'},
{ data: 'management_code', name: 'employee.management_code'},
{ data: 'job_role', name: 'employee.job_role'},
{ data: 'employee_type', name: 'employee.employee_type'},
],
columnDefs: [
{
"targets": [1, 4, 5], "visible": false, "searchable": false
}
],
order: [[2, 'asc']]
} );
// Add event listener for opening and closing details
$('#employeeTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = employeeTable.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
console.log(row.data());
row.child( template(row.data()) ).show();
tr.addClass('shown');
}
});
} );
</script>
#stop
In the script id details-template that is called, if I use {{ name }}, I get the error Use of undefined constant. But if I put some simple text instead, then everything works (but I don't get my data in this row details of course.
I have checked row.data in the console log and I have all the data available.
What is wrong?
Thanks.

Add delete button in Data table with Laravel

I' trying to add delete button in Data table column but it doesn't work. but my edit button works perfect. here i have post my QusLINK
edit button works perfect but delet button only errors
public function getRowDetailsData(PslCall $call)
{
$crews = Crew::Where('call_id',$call->id)->get();
return Datatables::of($crews)
->addColumn('action', function ($crew) {
return '<span class="glyphicon glyphicon-edit" data-toggle="tooltip" title="Edit"aria-hidden="true"></span>
<form action="{{ route(\'crews.destroy\', $crew->id)}}" method="POST"><input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn-xs form-btn confirmation-callback" data-placement="left"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
</form>';
})
->editColumn('id', 'ID: {{$id}}')
->removeColumn('id')
->editColumn('arrival_date', function ($crew) {
return $crew->arrival_date ? with(new Carbon($crew->arrival_date))->format('d-M-Y h:i') : '';
})
->filterColumn('arrival_date', function ($query, $keyword) {
$query->whereRaw("DATE_FORMAT(created_at,'%m/%d/%Y') like ?", ["%$keyword%"]);
})->make(true);
}
My Table like this
<table class="table table-striped table-bordered table-hover datas" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>NAME</th>
<th>GENDER</th>
<th>TYPE</th>
<th>ARRIVAL /DEPARTURE</th>
<th>ACTION</th>
</tr>
</thead>
</table>
again my script like this
var table = $('.datas').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('calls/'.$call->id.'/row-details-data') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": '<span class="btn btn-xs glyphicon glyphicon-download"></span>'
},
{data: 'crew_name', name: 'crew_name'},
{data: 'gender', name: 'gender'},
{data: 'crew_type'},
{data: 'arrival_date', "render":function(data, type, row){
switch(row.crew_type) {
case 'ONSIGNER' : return 'Arrival : '+ row.arrival_date; break;
case 'OFFSIGNER' : return 'Depart : '+ row.arrival_date; break;
default : return 'N/A';
}
}},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
} );
May
{!! Form::open(array('url' => '/crews/'.$crew->id, 'method' => 'delete')) !!}
<button type="submit" class="btn-xs form-btn confirmation-callback" data-placement="left"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
!! Form::close() !!}

Resources