Spring boot thymeleaf and datatables delete data - spring-boot

i'm learning spring boot with datatables. and now im success show data from MySQL to jquery datatables. and now im create CRUD, but my problem on this learning is delete data.
i'm understand with only table bootstrap create CRUD without datatables :
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Product Id</th>
<th>Name</th>
<th>Price</th>
<th>Delete</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.id}">Id</td>
<td th:text="${product.productId}">Product Id</td>
<td th:text="${product.name}">descirption</td>
<td th:text="${product.price}">price</td>
<td><a th:href="${'/product/delete/' + product.id}">Delete</a></td>
</tr>
</table>
easy only declare local variable thymeleaf on my html.
how delete data from datatables with confirmation dialog ?
this my code datatables :
$(document).ready (function() {
var table = $('#productsTable').DataTable({
"sAjaxSource": "/api/products",
"sAjaxDataProp": "",
"order": [[ 0, "asc" ]],
"columns": [
{ "mData": "id"},
{ "mData": "name" },
{ "mData": "price" },
{ "mData": "productId" },
{ "mData": "version" },
{
data: null,
defaultContent: 'Delete',
orderable: false
}
]
});
$('#btnDelete').on( 'click', 'a.remove', function (e) {
e.preventDefault();
editor.remove( $(this).closest('tr'), {
title: 'Delete Product',
message: 'Are you sure you wish to delete this data ?',
buttons: 'Delete'
} );
} );
});
products.html
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<title>Latihan Spring Boot</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="/js/product.js"></script>
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<h1 align="center">Products Table</h1>
<p><a class="btn btn-primary">Add Product</a></p>
<table id="productsTable" class="display">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Product ID</th>
<th>Version</th>
<th></th>
</tr>
</thead>
</table>
</div>
</body>
</html>

Try using jQuery confirm().
Update your code like so
$('#btnDelete').on( 'click', 'a.remove', function (e) {
e.preventDefault();
if(!confirm("Sure you want to delete!")){
return false;
}
editor.remove( $(this).closest('tr'), {
title: 'Delete Product',
message: 'Are you sure you wish to delete this data ?',
buttons: 'Delete'
} );
} );
});

Related

Sort table using jquery.ui and store the new position to database

I have a table named categories where I store the categories for an E-Commerce. This table has the following aspect:
And this is the user interface to admin the categories.
I want to make a system to sort this table using JQuery.UI.
This is what I tried, but it returns me 500 (Internal Server Error)
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
foreach($categories as $category)
<tr data-index="{{$category->id}}" data-position="{{$category->position}}">
<td class="table-text">{{$category->name}}</td>
<td class="table-text table-justified hide-mobile">
if ($category->visibility)
<i class="far fa-eye"></i>
else
<i class="far fa-eye-slash"></i>
endif
</td>
<td class="table-text table-opts">{{$category->position}}</td>
<td class="table-opts">
<div class="operations">
<a href="{{url('/admin/categories/'.$category->id.'/edit')}}" class="btn-edit pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
<i class="fas fa-edit"></i>
</a>
<a href="{{url('/admin/categories/'.$category->id.'/delete')}}" class="btn-delete btn-confirm pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
endforeach
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#table_content').sortable({
cancel: 'thead',
stop: () => {
var items = $('#table_content').sortable('toArray', {attribute: 'data-index'});
var ids = $.grep(items, (item) => item !== "");
$.post('{{ url('/admin/categories_list/reorder') }}', {
": $("meta[name='csrf-token']").attr("content"),
ids
})
.fail(function (response) {
alert('Error occured while sending reorder request');
location.reload();
});
}
});
});
</script>
And this is the controller function:
public function postCategoriesReorder(Request $request){
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
foreach ($request->ids as $index => $id){
DB::table('categories')->where('id', $id)->update(['position' => $index+1]);
}
return response(null, Response::HTTP_NO_CONTENT);
}
Consider the following example.
var tableData = [{
id: 1,
name: "Cat 1",
visibility: true,
position: 1
}, {
id: 2,
name: "Cat 2",
visibility: false,
position: 2
}, {
id: 3,
name: "Cat 3",
visibility: true,
position: 3
}, {
id: 4,
name: "Cat 4",
visibility: true,
position: 4
}, {
id: 5,
name: "Cat 5",
visibility: true,
position: 5
}];
$(function() {
function updateTable(data) {
$.each(data, function(i, r) {
var row = $("<tr>", {
"data-index": r.id
}).data("row", r).appendTo("#table_content");
$("<td>", {
class: "table-text"
}).html(r.name).appendTo(row);
$("<td>", {
class: "table-text table-justified hide-mobile"
}).html("<i class='fas fa-eye'></i>").appendTo(row);
if (!r.visibility) {
$(".fa-eye", row).toggleClass("fa-eye fa-eye-slash");
}
$("<td>", {
class: "table-text table-opts"
}).html(r.position).appendTo(row);
$("<td>", {
class: "table-opts"
}).appendTo(row);
$("<div>", {
class: "operations"
}).appendTo($("td:last", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/edit",
class: "btn-edit pV-8 pH-12",
title: "Editor",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-edit'></i>").appendTo($("td:last > div", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/delete",
class: "btn-delete btn-confirm pV-8 pH-12",
title: "Eliminar",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-trash-alt'></i>").appendTo($("td:last > div", row));
});
}
function gatherData(table) {
var rows = $("tbody > tr", table);
var item;
var results = [];
rows.each(function(i, el) {
item = $(el).data("row");
item.position = i + 1;
results.push(item);
});
return results;
}
updateTable(tableData);
$('#table_content').sortable({
cancel: 'thead',
start: (e, ui) => {
start = $('#table_content').sortable('toArray', {
attribute: 'data-index'
});
},
stop: () => {
ids = gatherData("table");
console.log(start, ids);
/*
$.post('/admin/categories_list/reorder', {
"csrf-token": $("meta[name = 'csrf-token']").attr("content"),
ids
})
.fail(function(response) {
alert('Error occured while sending reorder request');
location.reload();
});
*/
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" integrity="sha384-jLKHWM3JRmfMU0A5x5AkjWkw/EYfGUAGagvnfryNV3F9VqM98XiIH7VBGVoxVSc7" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
This should allow you to pass the new position for each ID to the script so the Database is updated.

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.

Display Data Got From JSON In Reactjs In Table

Here I wrote A code which fetches data from API http://fcctop100.herokuapp.com/api/fccusers/top/recent and displays Data in Form Of Table Which Looks Like Below In My Case As You Can See is Repeating For Every
But I want To Make It Look Like
Here Is What I Did So Far
var MainBox = React.createClass({
render:function(){
return(
<App/>
);
}
});
var App = React.createClass({
//setting up initial state
getInitialState:function(){
return{
data:[]
};
},
componentDidMount(){
this.getDataFromServer('http://fcctop100.herokuapp.com/api/fccusers/top/recent');
},
//showResult Method
showResult: function(response) {
this.setState({
data: response
});
},
//making ajax call to get data from server
getDataFromServer:function(URL){
$.ajax({
type:"GET",
dataType:"json",
url:URL,
success: function(response) {
this.showResult(response);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return(
<div>
<Result result={this.state.data}/>
</div>
);
}
});
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div>
{result}
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
});
ReactDOM.render(
<MainBox />,
document.querySelector("#app")
);
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>React Tutorial</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<div id="app"></div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</body>
</html>
The following should list all your items as a single row in your table, and only give you one table. One tip is to not use the index as the key for your map function. It's better to use some natural key or identifier in your result, some kind of id that will enable React better comparison of the components. A blog post describing this and some documentation.
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
{result}
</tbody>
</table>
</div>
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
);
}
});

Datatables Translation don't works

I have got a datatable using Datatables server-side. I have created and filled the table as shown below. Now I need to translate the datatable depending on the language , I found this example in the documentation :
$('#example').DataTable( {
language: {
search: "Search in table:"
}
} );
or loading translation :
$('#example').DataTable( {
language: {
url: '/localisation/fr_FR.json'
}
} );
But none of them works for me ! this is my code :
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "server-side-process",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
var oTable = $('#example').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"processing": true,
"serverSide": true,
"ajax": {...
https://datatables.net/plug-ins/i18n/
Below is a working example of two datatables. One using default English and one loading French as per the documentation: https://datatables.net/reference/option/language
JSFiddle link: https://jsfiddle.net/invalidname/mro9h48u/2/
$(document).ready(function() {
var oTable = $('#example').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
$(document).ready(function() {
var oTable = $('#exampleFR').DataTable({
"processing": true,
"serverSide": false,
"ajax": {
"url": "https://run.mocky.io/v3/b99908b5-61f9-4d41-9292-deaa510f3d93",
},
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/French.json"
},
"columns": [
{ "data": "name" },
{ "data": "adress" },
]
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<H1>
English table
</H1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>
<hr>
<hr>
<H1>
French table
</H1>
<table id="exampleFR" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>name</th>
<th>adress</th>
</tr>
</thead>
</table>

DataTables not working - Ignited Datatable Library

I have used ignited datable to integrate it in codeigniter but getting following error : DataTables warning: table id=example2 - Requested unknown parameter '0' for row 0.
$(document).ready(function() {
$('#example2').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "POST",
"sAjaxSource": "<?php echo base_url()?>auth/datatable"
} );
} );
Here is my html
<table id="example2" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
here is the json generated
{"draw":0,"recordsTotal":2,"recordsFiltered":2,"data":[{"email":"admin#admin.com","first_name":"Admin","last_name":"istrator"},{"email":"subhadeepgayen#gmail.com","first_name":"Subhadeep","last_name":"Gayen"}]}
can seem to find any solution :(
Hello you need only specify the columns
"columns": [
{ "data": "id" },
{ "data": "name" }
]
Have you tried this - http://ellislab.com/forums/viewthread/160896/
And also this - http://www.ahmed-samy.com/php-codeigniter-full-featrued-jquery-datatables-part-1/
Do let me know if you succeed.
Best

Resources