Delete button in Yajra Datatables in Laravel 5.7.9 - laravel

Hallo I have the MemberController with this action:
public function anyData()
{
$members = DB::table('members')
->select(['id','email','firstname','lastname','address','zip','city','phone','mobile','work','birthdate']);
return Datatables::of($members)
->addColumn('action', function ($id) {
return 'Edit
<button class="btn" data-remote="/member/' . $id->id . '">Delete</button>
'; })->make(true);
}
This is the JS Code to get the table with the datas:
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
}).$('.btn[data-remote]').on('click', function (e) {alert('test') })
;
</script>
The tables shows the data correctly, the edit link and delete button appears correctly but the action (at the moment only an alert) in the delete button is not working, when i click nothing happens.
I tryied also this on the javascript but nothing changed:
$('#datatable-member').DataTable().on('click', '.btn-delete[data-remote]', function (e) {alert('test') })

From Laravel framework for delete you need to have form validation by using X-CSRF Token. Try this to send a proper request for delete if you are using Laravel resource you can use below code, but make sure your datatable edit column are using the btn-delete class, as you are right now using the btn class.
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
});
$('#datatable-member').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
// confirm then
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#datatable-member').DataTable().draw(false);
});
});

Related

Unknown paramater name when calling data in datatable

When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Here is My controller
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = Post::select(DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();
return Datatables::of($data)
->addIndexColumn()
->make(true);
}
return view('task.index',);
}
Here is my view
<script type="text/javascript">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('team.task') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'name',
name: 'name',
orderable: false,
},
{
data: 'total',
name: 'total',
orderable: false,
},
{
data: 'finish',
name: 'finish'
},
]
});
});
</script>
When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Is something wrong in my controller or my view? thanks in advance
use this query
$data = DB::table('posts')->select('name', DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();

Can't get ID from URL Laravel

I have a datatable view that shows some post from user, I want to create a datatable with a button that can show all user post. But, when moving from all post lists to user post lists I cant get user_id from the URL.
I want to get the user_id using $request->route.
Here is my controller:-
public function index(Request $request)
{
if ($request->ajax()) {
$request->route('detail');
$data = Post::where('user_id', $this->route('detail'))->latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('detail');
}
Here is my route:-
Route::resource('detail', DetailController::class);
datatable code
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
columnDefs: [{
"targets": [0, 2, 3, 4, 5, 6], // your case first column
"className": "text-center",
},
],
language: {
paginate: {
next: '<span class="fas fa-arrow-right"></span>', // or '→'
previous: '<span class="fas fa-arrow-left"></span>' // or '←'
}
},
oLanguage: {
"oPaginate": {
next: '→', // or '→'
previous: '←' // or '←'
},
"sLengthMenu": "Tampilkan _MENU_ Item",
"sEmptyTable": "Tidak ada data",
"sInfoEmpty": "Tidak ditemukan",
"sLoadingRecords": "Sedang memproses - loading...",
"sInfo": "Menampilkan _START_ - _END_ dari _TOTAL_ Item",
"sSearch": "Cari:",
},
processing: true,
serverSide: true,
ajax: "{{ route('detail.index') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
If I change the $this->route('detail') into user_id value, the program will work as expected. Is there something wrong with my code? thanks in advance
Change this:-
$this->route('detail')
To:-
$request->get('details')
And your ajax method should be like this:
"ajax": {
'type': 'POST',
'url': '{{ route('detail.index') }}',
'data': {
detilas: 'your id',
},
}
your roure:
Route::post('detail', DetailController::class);

How to use HasManyThrough Relation in laravel datatable

I have three tables i am able to use relation between 2 tables easily. But when i am trying to access values from third table i mean trying to use hasManyThrough relation it is showing me always error. Do you have any idea how i can get value of third table column using middle table relation with first and last table.
System details
Linux
PHP 7
Laravel 5.3
Laravel-Datatables Latest Version
$('#mms-table').DataTable({
processing : true,
serverSide: true,
lengthMenu: [10,25,50,100],
order: [[1,'desc']],
ajax: '{!! url(LaravelLocalization::getCurrentLocale()."/admin/contact-management/contact-data") !!}',
columns: [
{ data: 'merchant.bank.name', name: 'merchant.bank_id', orderable: true },
{ data: 'merchant.merchant_id', name: 'merchant.merchant_id', orderable: true },
{ data: 'merchant.merchant_name', name: 'merchant.merchant_name', orderable: true },
{ data: 'contact.name', name: 'contact.name', orderable: true },
{ data: 'contact.email', name: 'contact.email', orderable: true },
{ data: 'city', name: 'city', orderable: true },
{ data: 'agent.name', name: 'agent.name', orderable: true },
{ data: 'action', name: 'action', orderable: false, searchable: false},
],
dom: 'Blfrptip',
buttons: [
{
extend: 'colvis',text: 'Show/Hide Columns'
}
],
oLanguage: {
sProcessing: "<img height='80' width='80' src='{{ url('public/images/loading.gif') }}' alt='loader'/>"
},
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
});

How to add the CSV,PDF buttons for a datatable using the Laravel Yajra plugin?

I am creating a datatable using Laravel's Yajra plugin. I am using the query builder form.(Like this Click here)
I wanna add buttons CSV,PDF to the datatable.
I know as per the documentation it can be done Like this
The problem is I have already done using query builder. Now I cannot change my code.
Kindly help me.
My jquery code is as follows:
<script type="text/javascript">
$(document).ready(function(){
$('body').addClass('sidebar-collapse');
var cat = "{{$cat}}";
$('#unreconcil_datatable').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('get_datatable',array('cat'=>$cat)) !!}',
columns: [
{ data: 'unrelines_uniq_num', name: 'unrelines_uniq_num' },
{ data: 'unrelines_bank_accno', name: 'unrelines_bank_accno' },
{ data:'unrelines_rficreated',name:'unrelines_rficreated'},
{ data: 'unrelines_roicreated', name: 'unrelines_roicreated' },
{ data: 'unrelines_bank_name', name: 'unrelines_bank_name' },
{ data: 'unrelines_line_number', name: 'unrelines_line_number' },
{ data: 'unrelines_state_date', name: 'unrelines_state_date' },
{ data: 'unrelines_trans_date', name: 'unrelines_trans_date' },
{ data: 'unrelines_trans_amount', name: 'unrelines_trans_amount' },
{ data: 'unrelines_unrec_amt', name: 'unrelines_unrec_amt' },
{ data: 'unrelines_desc', name: 'unrelines_desc' },
{ data: 'unrelines_variance', name: 'unrelines_variance' },
{ data: 'unrelines_cstatus', name: 'unrelines_cstatus' },
{ data: 'unrelines_assigned', name: 'unrelines_assigned' },
{ data: 'unrelines_created_date', name: 'unrelines_created_date' },
{data: 'tat', name: 'tat', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
My controller method is as follows:
public function getdatatable($cat){
$list = AvailableStatementLines::select([DB::raw(" '$cat' AS cat"),'unrelines_id','unrelines_uniq_num','unrelines_bank_accno','unrelines_rficreated','unrelines_roicreated','unrelines_bank_name','unrelines_line_number','unrelines_state_date','unrelines_trans_date','unrelines_trans_amount','unrelines_unrec_amt','unrelines_desc','unrelines_variance','unrelines_cstatus','unrelines_assigned','unrelines_created_date','unrelines_trans_type','unrelines_currency','unrelines_created_by_name','unrelines_ustatus',DB::raw("IF(unrelines_cstatus='closed', '',
ROUND(ABS(TIMESTAMPDIFF(MINUTE, date(unrelines_lastupdate), curdate()))/1440 - ABS(DATEDIFF(ADDDATE(curdate(), INTERVAL 1 -DAYOFWEEK(curdate()) DAY), ADDDATE(date(unrelines_lastupdate), INTERVAL 1 -DAYOFWEEK(date(unrelines_lastupdate)) DAY))) / 7 * 2 - (DAYOFWEEK(IF(date(unrelines_lastupdate) < curdate(), date(unrelines_lastupdate), curdate())) = 1) - (DAYOFWEEK(IF(date(unrelines_lastupdate) > curdate(), date(unrelines_lastupdate), curdate())) = 7),0)
) AS tat")])->where('unrelines_ucountry',Session::get('country'))->where('unrelines_display',1);
switch($cat){
case 'rfi':
$list1 = $list->where('unrelines_cstatus','Assigned');
break;
case 'roi':
$list1 = $list->where('unrelines_cstatus','Solution Provided');
break;
case 'closed':
$list1 = $list->where('unrelines_cstatus','Closed');
break;
default:
$list1 = $list->whereNotIn('unrelines_cstatus',['Closed','Assigned','Solution Provided']);
break;
}
return Datatables::of($list1)
->addColumn('unrelines_uniq_num',function($list1){
return "<input type='checkbox' class='uniqnums' name='uniquenum[]' value='".$list1->unrelines_id."'>".$list1->unrelines_uniq_num;
})
->addColumn('action',function($list1){
return "<button type='button' class='btn btn-xs btn-info viewLine' category=".$list1->cat." unrelines=".$list1->unrelines_id.">View</button>";
})
->setRowClass(function ($list1) {
return $list1->tat > 7 ? 'orange' : ($list1->tat > 5 ? 'red' : ' ');
})
->make(true);
}
You should apply this method in your controller.
public function html()
{
return $this->builder()
->columns([
'id',
'name',
'email',
'created_at',
'updated_at',
])
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'pdf', 'print', 'reset', 'reload'],
]);
}

Processing Json data with EXTJS

Java application sends to the front the following json data:
{"data":[{"id":1,"name":"","password":"xxxxxxxxxxxxxxxxxxx","roles":[{"id":1,"name":"Administrator"}],"username":"admin"}]}
In the front I have an user model like the following:
Ext.define('App.store.Users', {
extend: 'Ext.data.Store',
fields: [
{name: 'id', type: 'auto'},
{name: 'name', type: 'auto'},
{name: 'password', type: 'auto'},
{name: 'roles', type: 'auto'},
{name: 'username', type: 'auto'},
],
autoLoad: true,
proxy: {
type: 'ajax',
url: '/web/user',
reader: {
type: 'json',
root: 'data'
}
}
});
Edit:
I updated the code and this way the data is loaded.
Also i made a grid so I can show the results.
Ext.define('App.view.Home', {
extend: 'Ext.panel.Panel',
alias: 'widget.home',
title: 'Home',
layout: 'fit',
items: [
{
xtype: 'gridpanel',
store: 'Users',
title: 'Users grid',
columns: [
{text: 'Id', dataIndex: 'id' },
{text: 'Username', dataIndex: 'username', width : 200 },
{text: 'Role', dataIndex: 'roles', width : 200 },
{text: 'Name', dataIndex: 'name', width : 200 },
]
}
]
});
Now the question that remains is that the grid is showing [object Object] how could i be showing the part that i want from that object, as the name of the role
You need to change the reader type to JSON, This code is working for me:
Fiddle
Ext.application({
name: 'Fiddle',
launch: function() {
Ext.define('Users', {
extend: 'Ext.data.Store',
fields: ['id', {
name: 'username',
type: 'string'
}, {
name: 'name',
type: 'string'
}],
autoLoad: true,
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
Ext.create("Users", {
listeners: {
load: function() {
console.log("Loaded " + this.getCount() + " records");
}
}
});
}
});
I also removed the mappings as I don't think that you need them.
EDIT
In regards to the data showing in a grid, the 'roles' property in the JSON data is an array, that's why it's showing in the grid as object, I've updated the fiddle to show a possible way to get this information, But it's not the recommended method. You should probably look at associations in ExtJs for this.
Reviewing the guide on the Data Package may also help with this.
Ext.application({
name: 'Fiddle',
launch: function() {
Ext.define('Users', {
extend: 'Ext.data.Store',
fields: [{
name: 'id',
type: 'int'
}, {
name: 'username',
type: 'string'
}, {
name: 'name',
type: 'string'
}, {
name: 'roles',
type: 'auto'
}],
autoLoad: true,
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
root: 'data'
}
},
listeners: {
load: function(store, records) {
console.log("Loaded " + this.getCount() + " records");
}
}
});
var users = Ext.create("Users");
Ext.define('App.view.Home', {
extend: 'Ext.panel.Panel',
alias: 'widget.home',
title: 'Home',
layout: 'fit',
items: [{
xtype: 'gridpanel',
store: users,
title: 'Users grid',
columns: [{
text: 'Id',
dataIndex: 'id'
}, {
text: 'Username',
dataIndex: 'username',
width: 200
}, {
text: 'Role',
dataIndex: 'roles',
width: 200,
renderer: function(v, metadata) {
return v[0].name;
}
}, {
text: 'Name',
dataIndex: 'name',
width: 200
}]
}]
});
Ext.create('App.view.Home', {
renderTo: Ext.getBody()
});
}
});

Resources