Add delete button in Data table with Laravel - 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() !!}

Related

Laravel 5.8 and datatable form validation

I am using Laravel 5.8 and Yajra datatable package.
I have to build a dynamic form from the controller (it works well).
After submitting the form, when the validation fails, I want to display the old values in the form.
Display the form/datatable and validation work fine. I need the way to display the old values.
Controller (build the form) (just an excerpt as it works fine)
if (request()->ajax())
{
return datatables()
->of($memberships)
->addIndexColumn()
->addColumn('amount', function($data) use ($membership, $amounts) {
$link = '<input type="text" id="membership_id[]" name="membership_id[]" value="' . $data->id . '" style="width:100px" class="form-control">';
$link .= '<input type="number" id="amount[]" name="amount[]" value="">';
return $link;
})
->rawColumns(['amount'])
->make(true);
}
return view('my_blade', compact('memberships', 'id'));
My question here is How to set the value attribute in the amount input field when the validation fails?
my_blade (display datatable form) (just an excerpt as it works fine)
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" id="my_form" action="{{ route('my_submit_route') }}">
#csrf
<input type="text" id="id" name="id" value="{{ $id }}">
<table id="my_datatable" class="table table-hover table-striped table-responsive">
<thead class="crud-header">
<tr>
<th>No</th>
<th>Name</th>
<th>Description</th>
<th>Status</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="form-group row">
<div class="col text-center">
<button type="submit" class="btn btn-primary">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
#section('script')
<script>
$(document).ready(function() {
/* Start Datatable */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.noConflict();
$('#my_datatable').DataTable({
iDisplayLength: 100,
serverSide: true,
processing: true,
ajax: {
url: "{{ route('my_route', ['id' => $id]) }}",
type: 'GET',
},
columnDefs: [
{className: "dt-center", targets: "_all"}
],
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false},
{data: 'name', name: 'name'},
{data: 'given_name', name: 'given_name'},
{data: 'amount', name: 'amount'}
],
order: [[1, 'desc']]
});
/* End Datatable */
});
</script>
#endsection
My validation works fine. Just don't know how to display the old value when validation fails
My Controller (to process form submit)
/* get the array of membership IDs */
$membershipIDs = $request->membership_id;
$validate_array = [];
/* Loop through membership for validation */
for($i = 0; $i < count($membershipIDs); $i++)
{
$validate_array['amount.'. $i] = 'sometimes|nullable|numeric|gte:0';
}
$validator = Validator::make($request->all(), $validate_array);
if ($validator->fails())
{
/* Get the array of amounts */
$amounts = $request->amount;
// How to manage here to return in the form and display the old values and the error message on the failed fields?
}
else
{
//Process the form;
}
My question: How to manage in the controller to return in the form and display the old values and the error messages on the failed fields?
I also use the following for validation, the validation works well but I cannot display the old values in the form after the validation fails.
$this->validate($request, $validate_array);
Thanks
Try this in your controller:
if ($validator->fails()) {
return back()->withInput()->withErrors($validator);
}
Not sure if this also works in Laravel 5. But an alternate to this is:
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
Which works in Laravel 5

How to add link on datatables into data in table

I have data on table using Model View Controller :
controller :
<tbody>
#php
$no=0;
#endphp
#foreach ($pns as $i)
<tr class="even pointer">
<td class="a-center ">{{ ++$no }}</td>
<td class=" ">{{ $i->users->nama}}</td>
<td class=" ">{{ $i->NIP_lama}}</td>
<td class=" ">{{ $i->NIP_baru}}</td>
<td class=" ">{{ $i->TMT_CPNS}}</td>
<td class=" ">{{ $i->TMT_PNS}}</td>
<td class=" ">{{ $i->TMT_gol_ruang}}</td>
<td class=" ">{{ $i->master_golongan->golongan}}</td>
<td class=" ">{{ $i->master_jabatan->nama_jabatan}}</td>
</tr>
#endforeach
</tbody>
And the Controller :
public function pns() {
$pns = Data_pns::with('users')->get();
return view('admin.pns',['pns' => $pns]);
}
its run normally and not having error . now I want to add datatables yajra yajra feature , and it has 1 problem . I dont know how to add link :
<td class=" ">{{ $i->users->nama}}</td>
on the datatables :
My View :
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'users.nama', name: 'users.nama'},
{ data: 'NIP_lama', name: 'NIP_lama'},
{ data: 'NIP_baru', name: 'NIP_baru'},
{ data: 'TMT_CPNS', name: 'TMT_CPNS'},
{ data: 'TMT_PNS', name: 'TMT_PNS'},
{ data: 'TMT_gol_ruang', name: 'TMT_gol_ruang'},
{ data: 'master_golongan.golongan', name: 'master_golongan.golongan'},
{ data: 'master_jabatan.nama_jabatan', name: 'master_jabatan.nama_jabatan'},
],
});
})
</script>
#endpush
and my controller like this :
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->make(true);
}
edited this controller
and my controller like this :
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->addColumn('Nama', function ($pns) {
return ''.$pns->users->nama.'';
})
->make(true);
}
but this output in view " <#a href="project/pns/5">test" with out #
my Question how to add link like
<td class=" ">{{ $i->users->nama}}</td>
on datatbles ?
you already halfway there, you need to set the 'Nama' columns as raw, if you're returning an html content like this
public function indexDataTables_pns()
{
$pns = Data_pns::with('users','master_golongan','master_jabatan')->get();
return Datatables::of($pns)->addIndexColumn()
->addColumn('Nama', function ($pns) {
return ''.$pns->users->nama.'';
})
->rawColumns(['Nama'])
->make(true);
}

my GET method is not supported for this route. (for delete) Laravel 5.8

I have table view with datatables yajra . before i using datatable my delete is normaly ,but after using datatables my delete have error like this
The GET method is not supported for this route. Supported methods: DELETE.
i using route delete but its didint work . can you correct my code ?
view
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<thead>
{{-- <th>No</th> --}}
<th>Nama Alat</th>
<th>Waktu</th>
<th>User Input</th>
<th>Action</th>
<th>Edit</th>
<th>Hapus</th>
<th>Tanggal</th>
</thead>
</tr>
#push('scripts')
<script>
$(function () {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('adminshow1dt') !!}',
columns: [
{data: 'alat.nama_alat', name: 'alat.nama_alat'},
{data: 'status', name: 'pemeliharaan.status'},
{data: 'user.name', name: 'user.name'},
{data: 'action', name: 'action', orderable: false, searchable: false},
{data: 'edit', name: 'edit', orderable: false, searchable: false},
{data: 'hapus', name: 'hapus', orderable: false, searchable: false},
{data: 'created_at', name: 'created_at'},
],
});
})
</script>
#endpush
my controller and route
public function show()
{
// $pemeliharaan = Pemeliharaan::all();
// $pemeliharaan = Pemeliharaan::find($id);
$pemeliharaan = Pemeliharaan::with(['user', 'alat'])->where('status', 'harian')->get();
return view('admin.view_harian', ['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTablesh()
{
$pemeliharaan = Pemeliharaan::with(['user', 'alat'])->where('status', 'harian')->get();
return Datatables::of($pemeliharaan)
->addColumn('action', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-eye-open"></i> View Data';
})
->editColumn('edit', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-edit"></i> Edit';
})
->editColumn('hapus', function ($pemeliharaan) {
return '<i class="glyphicon glyphicon-remove-circle"></i> Hapus';
})
->rawColumns(['hapus' => 'hapus', 'action' => 'action', 'edit' => 'edit'])
->make(true);
}
Routes
Route::delete('/admin/delete1/{id}', 'adminController#destroy1' )->name('delete1');
Route::get('admin/show1', 'adminController#show')->name('adminshow1');
Route::get('admin/show1-dt', 'adminController#indexDataTablesh')->name('adminshow1dt');
can you correct this code plz ?
Try add a form to your action column, notice we have method_field "delete" and csrf_field
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='admin/delete1/$pemeliharaan->id' method='POST'>
$c
$m
<button style='margin-left:10px; width: 150px;' type='submit'
class='btn btn-xs btn-danger'>
<i class='glyphicon glyphicon-remove-circle'></i> Hapus
</button>
</form>"
yaa, ok I got it actually a tag not support delete method if you want to use delete method then you have to use form else use get method in a tag.
Route::get('/admin/delete1/{id}', 'adminController#destroy1' )->name('delete1');
Hope this helps :)

How to showing data on table with datatables 'yajra'

I following this tutorial : How to route in Laravel DataTables
its so simple , but i cant do it . after i set my controller and my route and view , its not showing data and and table. in the table i have a button like'action' how i can take this comand to this button ?
can you check my faulth query
Route::get('user/show1', 'userController#show')->name('usershow1');
Route::get('user/show1-dt', 'userController#indexDataTables')->name('usershow1dt');
controller
public function show()
{
$pemeliharaan = Pemeliharaan::with(['user','alat'])->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}
public function indexDataTables()
{
$pemeliharaan = Pemeliharaan::query();
// return DataTables::eloquent($pemeliharaan)->toJson();
return Datatables::of($pemeliharaan)->make(true);
}
and i have a view like this . the page number,search and pagination is showing at view ,but this data not showing. can you correctted this view ?
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="table">
<tbody><tr>
<th>No</th>
<th>Nama Alat</th>
<th>status</th>
<th>User Input</th>
<th>Action</th>
<th>Tanggal</th>
</tr>
{{-- #php ---> before i suing datatables my view like that
$no=0;
#endphp
#foreach ($pemeliharaan as $i)
<tr>
<td>{{ ++$no }} </td>
<td>{{ $i->alat->nama_alat}}</td>
<td>{{ $i->status}}</td>
<td>{{ $i->user->name}}</td>
<td> Lihat Data</span> </td>
<td>{{ $i->created_at}}</td>
</tr>
#endforeach --}}
</tbody></table>
</div>
.
.
#endsection
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('usershow1dt') !!}',
columns: [
{ data: 'nama_alat', name: 'nama_alat'},
{ data: 'status', name: 'status'},
{ data: 'User Input', name: 'nama'},
{ data: 'Action', name: 'name'},//here my button
{ data: 'Tanggal', name: 'created_at'},
],
});
})
</script>
#endpush
Try This:
public function show() {
$pemeliharaan = Pemeliharaan::where('user','alat')->where('status','harian')->get();
return view('users.view_harian',['pemeliharaan' => $pemeliharaan]);
}

Laravel Yajra DataTable - Fetch content via Ajax with supplied search parameters

After searching as to how to fill up a Yajra DataTable with data from an ajax call with user supplied search parameters, I came to this page for the official documentation.
It has a code snippet as follows...
$builder->ajax([
'url' => route('users.index'),
'type' => 'GET',
'data' => 'function(d) { d.key = "value"; }',
])
However, I cannot make anything out of it. Where does the $builder variable come from? How do I use the data received from the Ajax call to fill up the table? This page lists the callback functions with no details.
What I need
A full-blown example of how to fill up my data table with data received from an Ajax call initiated by the search button #btn_search after selecting a value from the drop-down #param.
For simplicity, lets assume that the table structure looks like...
<select id="param">
<option value="">Select </option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn_search" value="Search">Search</button>
<table>
<thead>
<tr>
<th>Serial</th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
</table>
The controller method that returns the data...
<?php
public function getBasicData()
{
$users = User::select(['id','name','email','address']);
return Datatables::of($users)->make();
}
The user selects a value from the dropdown and clicks on the search button. In the actual scenario, several dropdowns are there to collect the search parameters. Relevant jQuery code is...
$("#btn_search").click(function() {
var param_value = $("#param").val().trim();
// make ajax call probably
});
How can I make the Ajax call inside the click handler and fill up the data table with the received data?
The $builder variable is the class id of the table that would view the information ,
Here is an example :
<table id="data" class="table table-bordered table-hover" >
<thead>
<tr class="table-head">
<th>#</th>
<th>namr</th>
<th>email</th>
<th>date</th>
<th>auth</th>
<th>control</th>
<th>control</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<th> </th>
<th> </th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tfoot>
</table>
and this is ajax code
<script type="text/javascript">
var lastIdx = null;
var table = $('#data').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('/adminpanel/users/data') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'admin', name: 'isadmin'},
{data: 'edit', name: 'edit', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
"language": {
"url": "{{ Request::root() }} /admin/cus/Arabic.json"
},
"stateSave": false,
"responsive": true,
"order": [[0, 'asc']],
"pagingType": "full_numbers",
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: 25,
fixedHeader: true,
"oTableTools": {
"aButtons": [{
"sExtends": "csv",
"sButtonText": "ملف إكسل",
"sCharSet": "utf16le"
},
{
"sExtends": "copy",
"sButtonText": "نسخ المعلومات",
},
{
"sExtends": "print",
"sButtonText": "طباعة",
"mColumns": "visible",
}
],
"sSwfPath": "{{ Request::root() }} /website/admin/cus/copy_csv_xls_pdf.swf"
},
"dom": '<"pull-left text-left" T><"pullright" i><"clearfix"><"pull-right text-right col-lg-6" f > <"pull-left text-left" l><"clearfix">rt<"pull-right text-right col-lg-6" pi > <"pull-left text-left" l><"clearfix"> '
,initComplete: function ()
{
var r = $('#data tfoot tr');
r.find('th').each(function(){
$(this).css('padding', 8);
});
$('#data thead').append(r);
$('#search_0').css('text-align', 'center');
}
});
table.columns().eq(0).each(function(colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
});
table.columns().eq(0).each(function(colIdx) {
$('select', table.column(colIdx).header()).on('change', function() {
table
.column(colIdx)
.search(this.value)
.draw();
});
$('select', table.column(colIdx).header()).on('click', function(e) {
e.stopPropagation();
});
});
$('#data tbody')
.on( 'mouseover', 'td', function () {
var colIdx = table.cell(this).index().column;
if ( colIdx !== lastIdx ) {
$( table.cells().nodes() ).removeClass( 'highlight' );
$( table.column( colIdx ).nodes() ).addClass( 'highlight' );
}
} )
.on( 'mouseleave', function () {
$( table.cells().nodes() ).removeClass( 'highlight' );
} );
</script>
this is a full table with ajax example ,like Yajara documentation help .

Resources