how to add alert on-click button Submit datatables yajra ? Laravel - laravel

I have a table data , this table have function delete button .
this button is successfully delete but i need to add alert on-click confirmation to delete like this :
<a href="delete.php?id=<?=$row['id']; ?>"
onclick="return confirm('Anda yakin mau menghapus item ini ?')">[Hapus]</a>
but i using datatales serverside i dont know where i put this onclick
its my function delete
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.'';
})
->editColumn('edit', function ($pns) {
return '<i class="glyphicon glyphicon-edit"></i>';
})
->editColumn('hapus', function ($pns) {
// THIS START HERE FOR DELETE FUNCTION
$c = csrf_field();
$m = method_field('DELETE');
return "<form action='/delete/$pns->id' method='POST'>
$c
$m
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
</form>";
})
->rawColumns(['Nama' => 'Nama','hapus' => 'hapus','action' => 'action','edit'=>'edit'])
->make(true);
}
where i can put this onclick and this message ?

you can use it on your delete form's button like
<button style='margin-left:10px; width: 30px;' type='submit'
class='btn btn-xs btn-danger delete' onclick='return confirm("Anda yakin mau
menghapus item ini ?")'>
<i class='glyphicon glyphicon-remove-circle'></i>
</button>
or add a class to your form and use confirmation before submitting the form
<form action='/delete/$pns->id' method='POST' class='delete-form'>
now add this script in your view file
<script>
$('.delete-form').submit(function(event){
if(!confirm('Anda yakin mau menghapus item ini ?')){
event.preventDefault();
}
});
</script>

Related

How do I implement Sweet Alert by RealRashid to confirm Record Delete in controller destroy() method?

public function destroy(Company $company)
{
Alert::question('Delete Record?', 'Cannot Undo! Are You Sure?');
if (session('status')) {
$company->delete();
}
return back()->with('status', 'Company Deleted!');
}
At the moment the record deletes with or without the Sweet Alert confirmation. I want the record deleted only after the Sweet Alert confirmation is clicked.
Just change button type from submit to button and trigger vai javascript function
<form action="{{ route('orders.destroy', $row->id) }}" method="post" class="d-inline">#csrf#method('DELETE')<button type="button" class="btn btn-sm btn-danger confirm-delete"><i class="fas fa-times"></i></button></form>
$(document).on('click', 'button.confirm-delete', function () {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$(this).parent('form').trigger('submit')
} else if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info')
}
});
});
I was searching for an answer like you, and I came up with something works perfectly!
If the user is trying to delete something, it will show him warning alert to confirm the delete.. once he clicks on yes it will delete it and show another alert with success of deletion.
Here is how you can do it:
after installing RealRashid/Sweet-Alert and publish it you need to do this:
In your view:
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
//Sweet alert stylesheet
<link rel="stylesheet" href="sweetalert2.min.css">
</head>
<body>
//refer to rashid's docs
#include('sweetalert::alert')
//The delete button
<a class="btn btn-primary mb-1" href="{{ Route('movies.edit', $movie) }}">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ Route('movies.destroy', $movie) }}" method="post" class="ms-2 mb-1">
#csrf
#method('DELETE')
//The 'confirm' class is important to use in the JavaScript code
<button class="btn btn-danger confirm" type="submit">
<i class="bi bi-trash"></i>
</button>
</form>
//Add Sweetalert script lib
<script src="sweetalert2.all.min.js"></script>
<script>
//the confirm class that is being used in the delete button
$('.confirm').click(function(event) {
//This will choose the closest form to the button
var form = $(this).closest("form");
//don't let the form submit yet
event.preventDefault();
//configure sweetalert alert as you wish
Swal.fire({
title: 'هل أنت متأكد؟',
text: "لا يمكنك التراجع عن حذف الفلم",
cancelButtonText: "إلغاء",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'حذف'
}).then((result) => {
//in case of deletion confirm then make the form submit
if (result.isConfirmed) {
form.submit();
}
})
});
</script>
</body>
</html>
after doing the above code in your view, head to your controller and do this:
//Add use statement for rashid's alert
use RealRashid\SweetAlert\Facades\Alert;
//in your destroy function you can do this
public function destroy(Movie $movie)
{
$movie->genres()->detach();
$movie->delete();
return redirect()->route('movies.index')->with('success', 'تم حذف الفلم بنجاح!');
}
//with success will trigger rashid's alert to pop up and you customize the message in 'with' statement!
That's it! you don't need to do anything else or add Alert::success in the controller.. withSuccess works just fine.

Yajra Datatables with custom buttons

I am using the Yajra Datatables with server side rendering in a Laravel project. But I want to add some custom buttons to the columns that will have Vue #click functions. I am trying to add like this but the click it's not working.
->addColumn('action', function($user){
$btn = '<a #click="delete_user('.$user->id.')"><i class="fa fa-times font-20 deleteUser"></i></a>';
return $btn;
})
Have you tried v-on:click in code. Can you please show the vue js code.
I have had the same problem, I do not want to reboot to the ease of working with Yajra or to the power of Vue. I have fixed it by calling the function directly from the Vue instantiated object.
<button id="btn_entrada_edit" class="btn btn-sm dropdown-item text-primary" onclick="modal_edit_entrada.edit_entrada(' . $entrada->id . ')" ><i class="fas fa-edit"></i> Editar</button>
This is on my controller, other js functions like copying the passw and loging as user are working fine. The only thing not working is Vue click:
public function getBasicData()
{
$user=User::all();
return Datatables::of(User::query())
->addIndexColumn()
->addColumn('view_user', function($user){
$btn =
''.$user->name.'';
return $btn;
})
->addColumn('action', function($user){
if(Cache::has('user-is-online-' . $user->id))
$btn3='<i class="fa fa-circle font-16 onlineStatus online"></i>';
else $btn3 ='<i class="far fa-circle font-16 onlineStatus offline"></i>';
$btn1 = '<a v-on:click="delete_user('.$user->id.')"><i class="fa fa-times font-20 deleteUser"></i></a>';
$btn2 = '<i class="fa fa-user font-20"></i><input id="myInput'.$user->id.'" class="copyPassInput" value="'.$user->real_password.'"><i onclick="myFunction('.$user->id.')" title="'.$user->real_password.'" class="fa fa-eye font-20 copyPassIcon"></i>';
$btn4='<div class="d-flex">'.$btn2.' '.$btn1.' '.$btn3.'</div>';
return $btn4;
})
->rawColumns(['view_user','action'])
->make();
}

Is there other way to set url using route?

i'm just starting to learn ajax laravel im just following a tutorial then it not working for me. thanks
my ajax looks like this:
$(document).ready(function(){
$('#courseTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{{ route('courses.index') }}}",
},
then in routes:
Route::resource('courses', 'CourseController');
then for my coursecontroller:
public function index()
{
// $courses = Course::orderBy('description','asc')->paginate(8);
if (request()->ajax()) {
return datatables()->of(Course::latest()->get())
->addColumn('action', function($data){
$button = '<button type="button" name="edit" id="'.$data->courseID.'"
class="edit btn btn-warning btn-sm">Edit</button>';
$button .= ' ';
$button .= '<button type="button" name="delete" id="'.$data->courseID.'"
class="delete btn btn-warning btn-sm">Delete</button>';
return $button;
})
->rawColumns(['action'])
->make(true);
}
return view('registrar.courses.index');
// ->with('courses', $courses)
}
this error shows up like this:
app.js:16034 GET http://odrs.test/%7B%7B%7B%20route('courses.index')%20%7D%7D%7D?draw=1&colum 404 (Not Found)
it's impossible to write a blade template in a separate javascript file.
you have probably 2 ways to do it:
join your eventListener in your blade view as a child.
transfer your JS file to your views file, change its extension to blade.php and include it in the view between script tags:
<script>
#include("my-view-js")
</script>

Yajra DataTable addColumn

I use yajra datatable but i've get problem when I use the method "addColumn".
the one I use that method is work properly, but the other doesn't
this is my source code :
->addColumn('action', function($arrProduct){
return
'<center><a class="btn btn-success btn-sm" href="'.route('packaging.edit',['id' => $arrProduct['id'], 'product_id'=> $arrProduct['product_id']]).'">
<i class="fa fa-refresh"></i> Proses</a></center>';
})
->addColumn('status', function($arrProduct){
if($arrProduct['status_produksi']){
return ucwords($arrProduct['status_produksi']);
}else{
$tag = "<center><a class='btn btn-danger btn-sm'>
<i class='fa fa-refresh'></i>Belum Diproses</a></center>";
return $tag;
}
})
->make(true);
and this is the problem :
one of them (column action) is work properly, but why in the other (column status) the "addColumn" doesn't work?
pls somebody help me.. thank's anyway
Add ->rawColumns(['status', 'action'])
before ->make(true);

How to use variable data after Ajax Call Success - Laravel

I created a small file manager to manage my files. On the one hand, the folder structure is shown thanks to JsTree. On the right I would like that based on the click on the left folder I was shown the files contained in that folder.
At the click an Ajax call is made which calls the selectFiles method to go through the routes. Now in the console i see the correct data, but i don't know how to use it into foreach in the blade.
AJAX:
// chiamata Ajax per selezionare files in base all'id
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
console.log('Succes!',data);
},
error : function(err) {
console.log('Error!', err);
},
});
});
DocumentiController.php:
/**
* Selzionare files in base all'id della cartella
*/
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json(compact('files'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
Route:
Route::post('archivio_documenti/{id}/selectFiles', 'DocumentiController#selectFiles');
Update:
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
OK, the foreach of yours is a bit complex, but the idea itself is simple: recreate the foreach loop from your Blade in Javascript and append the result to the DOM.
In your success callback you could e.g. do this:
$('#treeview').on("select_node.jstree", function (e, data) {
var id = data.node.id;
$.ajax({
type: 'POST',
url: 'archivio_documenti/+id+/selectFiles',
data: {id:id},
success: function(data) {
// Build the HTML based on the files data
var html = '';
$.each(data, function(i, file) {
html += '<div class="file" id="file_' + file.id + '">' + file.updated_at + '</div>';
});
// Append the built HTML to a DOM element of your choice
$('#myFilesContainer').empty().append(html);
},
error : function(err) {
console.log('Error!', err);
},
});
});
Obviously, this is simplified and you'd need to use the HTML structure you've shown us in the foreach loop above, but the idea is the same: (1) loop through your files in the data object and build the HTML structure row by row, (2) put the whole HTML block in the DOM, wherever you need it to be displayed after the user clicked on a folder.
Alternative:
If you'd like to keep the foreach loop in Blade instead of of Javascipt, you could move the loop to a separate blade:
folder_contents.blade.php
#foreach($files as $key => $file)
<div id="myDIV" class="file-box">
<div class="file">
{!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
<button type="submit" class="#" style="background: none; border: none; color: red;">
<i class='fa fa-trash' aria-hidden='true'></i>
</button>
{!! Form::close() !!}
<i class='fa fa-edit' aria-hidden='true'></i>
<input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
<i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i>
<a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
<span class="corner"></span>
<div class="icon">
<i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
</div>
<div class="file-name">
{{$file->file}}
<br>
<small>Update: {{$file->updated_at}}</small>
</div>
</a>
</div>
</div>
#endforeach
Then, in your controller:
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
// Save the view as string
$view = view('folder_contents.blade.php', compact('files')))->render();
// Pass the ready HTML back to Javasctipt
return response()->json(compact('view'));
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}
you must set header for ajax
headers: {
'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
and in Controller
public function selectFiles(Request $request){
try{
$id = $request->id;
$files = \App\Documento::where('cartella_id',$id)->get();
return response()->json($files);
}
catch(\Exception $e){
echo json_encode($e->getMessage());
}
}

Resources