tomas95go's avatar

How to make a delete confirmation Window with Sweet Alert

Let me be clear for you people :), I already found the answer to this issue in this link

https://laracasts.com/discuss/channels/laravel/confirm-delete-using-sweetalert

The problem is, I do not know how to implement that answer in my code, I just start using Sweet Alert today and I manage to setup basic messages like "Success! You are now loged in" kind of stuff.

Also I try to get an answer on Google, not having result's cause I don't know JavaScript either.

So, I'm asking for help here because I only need this kind of Window for my project (at least for now).

Laravel version: 5.4.19

S.O: Windows 10.

Enviroment: virtualized Homestead version 2.2.2 on a VirtualBox VM.

Additional packages: Laravel Collective for the forms and Sweet Alerts as I mentioned at the beginning of the thread.

This is my code:

ControladorProductos.php: (ProductsController in english)

<?php

    public function destroy($id)
    {
        
        $productos = Producto::find($id);

        if($productos != null) {

            $productos->delete();

            return redirect()->action('ControladorProductos@index');

        }

        return redirect()->action('ControladorProductos@index');

    }
}

mostrar.blade.php (This is the view where I show the list of my products)

@extends('layouts.maestro')

@section ('contenido')

<hr>

@include('sweet::alert')

        <table class="table table-responsive">

            <th><a href="{{('/administrarStock/create')}}"><button type="button" class="btn-primary">Agregar un producto nuevo</button></a></th>

            <th>

            {!! Form::open(['method'=>'GET','url'=>'administrarStock','class'=>'navbar-form navbar-left','role'=>'search']) !!}

                <div class="input-group custom-search-form">

                  <input type="text" name="search" class="form-control" placeholder="Search..">

                  <span class="input-group-btn"> 

                    <button type="submit" class="btn btn-primary">

                  </span>

                    </button>

                 </div>   

              {!! Form::close() !!}  

            </th>

        </table>

<hr>
        <table class="table">

              <thead>

                <tr>

                  <th>Codigo</th>

                  <th>Descripcion</th>

                  <th>Cantidad</th>

                  <th >Acciones</th>

                  <th>Precio Unitario</th>

                </tr>

              </thead>

              <tbody>

                <tr>

                @foreach ($productos as $producto)

                  <td>{{$producto->codigo}}</td>

                  <td>{{$producto->descripcion}}</td>

                  <td>{{$producto->cantidad}}</td>

                  <td> 

                        <a href="{{ route('administrarStock.edit',$producto->id) }}"> <button class="btn-primary"> Editar </button></a> 

                        {!! Form::open(['method' => 'DELETE','route' => ['administrarStock.destroy', $producto->id],'style'=>'display:inline']) !!}

                        {!! Form::submit('Eliminar', ['class' => ' btn-danger']) !!}

                        {!! Form::close() !!}

                  </td>

                  <td> </td>



                </tr>

                @endforeach



              </tbody>

        </table>  

        {!! $productos->render() !!}     
        
@endsection ('contenido')

I think that's all you guys need to help me, I hope that I'm being clear :D, thanks in advance.

0 likes
9 replies
Cronix's avatar

You need to show your sweet alert js code. The above doesn't really help.

Screenbeetle's avatar

I've moved away from Sweet alert in the past year or so but I have this from an older project:

If you are using Laravel Collective then:

// set up a relevant id in your form
{{ Form::open(['route' => ['delete-me', $model->id], 'method' => 'DELETE', 'id' => 'confirm_delete']) }}

// then listen out for that id in your SA script
<script type="text/javascript">
    $(document).ready(function(){
        $( "#confirm_delete" ).submit(function( event ) {
            event.preventDefault();
            swal({
                title: 'Are you sure?',
                text: "Please click confirm to delete this item",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger',
                buttonsStyling: true
            }).then(function() {
                    $("#confirm_delete").off("submit").submit();
            }, function(dismiss) {
                // dismiss can be 'cancel', 'overlay',
                // 'close', and 'timer'
                if (dismiss === 'cancel') {
                    swal('Cancelled', 'Delete Cancelled :)', 'error');
                }
            })
        });
    });
</script>
2 likes
Screenbeetle's avatar

PS. I wouldn't rely on SA to save your app from accidental deletes mind! Where relevant you definitely need foreign key constraints as well.

Sorry if that's spoon feeding but I have an old website which suffered just that issue (staff were able to delete products which now no longer show on orders because I didn't know what I was doing in 2011 :-).

tomas95go's avatar

@Cronix what code are you talking about? The css and js? or the function I tried to do? This last thing, I erase that function cause I didn't make it to work,I tried to apply the function that it's in the link I put on the thread.

@Screenbeetle

I put the peace of code u gave me and adapt it to my routes, but it is still not working.

{{ Form:: open(['method' => 'DELETE','route' => ['administrarStock.destroy', $producto->id], 'id' => 'confirm_delete']) }}

                        {!! Form::submit('Eliminar', ['class' => ' btn-danger']) !!}

                          <script type="text/javascript">
                            $(document).ready(function(){
                                $( "#confirm_delete" ).submit(function( event ) {
                                    event.preventDefault();
                                    swal({
                                        title: 'Are you sure?',
                                        text: "Please click confirm to delete this item",
                                        type: 'warning',
                                        showCancelButton: true,
                                        confirmButtonColor: '#3085d6',
                                        cancelButtonColor: '#d33',
                                        confirmButtonText: 'Yes, delete it!',
                                        cancelButtonText: 'No, cancel!',
                                        confirmButtonClass: 'btn btn-success',
                                        cancelButtonClass: 'btn btn-danger',
                                        buttonsStyling: true
                                    }).then(function() {
                                            $("#confirm_delete").off("submit").submit();
                                    }, function(dismiss) {
                                        // dismiss can be 'cancel', 'overlay',
                                        // 'close', and 'timer'
                                        if (dismiss === 'cancel') {
                                            swal('Cancelled', 'Delete Cancelled :)', 'error');
                                        }
                                    })
                                });
                            });
                        </script>

                        

                        {!! Form::close() !!}
Screenbeetle's avatar

Some things to consider:

  • Are you getting any JS errors? Clashing with another script maybe?
  • Are you including the SA library (in blade page/layout) before making the call?
  • Does the delete route work without SA?

I just need to say also ... you asked

@Cronix what code are you talking about?

He did say very clearly :-)

You need to show your sweet alert js code

tomas95go's avatar

@Screenbeetle

Does the delete route work without SA?

Yep it is working perfectly, what I want to avoid is making a redirect to another view just for the confirmation of the delete. I want this alert because I do not want to interrump the "flow" of the program and offer a better user exprience, I'm going to do it if I do not have another alternative though.

By the way, the code that I copy from you yesterday is not generating a button, I do not know if it is my mistake or what, but I add the button like a showed you in my comment also I past that code in the view with the form dunno if the Script goes there.

Are you including the SA library (in blade page/layout) before making the call?

Yes, I'm including the '@include('sweet::alert')' in the view if that what u mean. In the controller I got it this way. And in the masterlayout I got the references:

" <script src="dist/sweetalert.min.js"></script>" "<link rel="stylesheet" type="text/css" href="dist/sweetalert.css">" "<script src="../../dist/js/bootstrap.min.js"></script>"

public function destroy($id)
    {
        
        $productos = Producto::find($id);

        if($productos != null) {

            $productos->delete();

            Alert::success('Do you want to delete this record','Confirmation');

            return redirect()->action('ControladorProductos@index');

        }

        return redirect()->action('ControladorProductos@index');

    }

Are you getting any JS errors? Clashing with another script maybe?

I don't think so, I can't tell you that exactly, because I don't know how a JS error is desplayed :(, the window is just popping out, and the record is being deleted anyways, not waiting for the user to confirm it.

@Cronix, @Screenbeetle I'm not getting it quite clear for being new to this stuff, I think you guys refer to the code storage in my "Public/dist/", but wich one is it? I got two files with js: "sweetalert-dev.js" and "sweetalert.min.js",I got a third file but that one is for the css. I have to say I did not touch any of this three files.

@Screenbeetle if u say that I can not relay on Sweet Alert for preventing an user to delete a record accidentally, how can I do it?

Oh and I did not thank you two for answering yesterday, sorry, thanks for helping me :D.

Screenbeetle's avatar

Hi again tomas95go

My example is to use separately from your Laravel flash messaging.

This line: Alert::success('Do you want to delete this record','Confirmation'); looks like it will trigger sweet alert after hitting your route? You want a SA to trigger before hitting your route.

So a simple SA solution is just include my above code in your page or layout next to your other success SA. Then if you include the confirm_delete id in a form it should trigger:

So a simple form example:

{{ Form::open(['route' => ['delete-me', $model->id], 'method' => 'DELETE', 'id' => 'confirm_delete']) }}
<button type="submit">
Delete
</button>
{{ Form::close() }}

Then in the footer of your layout / view:

<script type="text/javascript">
    $(document).ready(function(){
        $( "#confirm_delete" ).submit(function( event ) {
            event.preventDefault();
            swal({
                title: 'Are you sure?',
                text: "Please click confirm to delete this item",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'No, cancel!',
                confirmButtonClass: 'btn btn-success',
                cancelButtonClass: 'btn btn-danger',
                buttonsStyling: true
            }).then(function() {
                    $("#confirm_delete").off("submit").submit();
            }, function(dismiss) {
                // dismiss can be 'cancel', 'overlay',
                // 'close', and 'timer'
                if (dismiss === 'cancel') {
                    swal('Cancelled', 'Delete Cancelled :)', 'error');
                }
            })
        });
    });
</script>
tomas95go's avatar
tomas95go
OP
Best Answer
Level 2

@Screenbeetle Hi!

Yes, that's exactly how I did it (when I remove the Alert reference from the controller), the window is still not popping out, I'm starting thinking may be I installed Sweet-Alert in a wrong way and that's why I can do simple stuff but no use functions like the one in your code.

EDIT:

@Screenbeetle

Don't kill me please for what I'm about to say since I did not know I have to add a reference to Jquery, so I add this references at the top of my "master layout":

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

And the Window is popping out, just not deleting the record.

EDIT 2:

@Screenbeetle

I have managed to found a code that is working now, deleting the query after the confirmation. Thank you for all your help anyway :).


<script type="text/javascript">
                                         document.querySelector('#confirm_delete').addEventListener('submit', function(e) {
                                    var form = this;
                                    e.preventDefault();
                                    swal({
                                        title: "¿Estas seguro que deseas eliminar este producto?",
                                        text: "Si eliminas este producto, no podras recuperarlo",
                                        type: "warning",
                                        showCancelButton: true,
                                        confirmButtonColor: '#DD6B55',
                                        confirmButtonText: '¡Si, estoy seguro!',
                                        cancelButtonText: "Cancelar",
                                        closeOnConfirm: false,
                                        closeOnCancel: false
                                    },
                                    function(isConfirm) {
                                        if (isConfirm) {
                                            swal({
                                                title: '¡Eliminado!',
                                                text: 'El producto ha sido eliminado con exito!',
                                                type: 'success'
                                            }, function() {
                                                form.submit();
                                            });
                                        } else {
                                            swal("Cancelado", "Tu producto no ha sido eliminado", "error");
                                        }
                                    });
                                });
                            </script>  

Screenbeetle's avatar

Ha - missing Jquery - one to remember. Good that you solved it :-)

1 like

Please or to participate in this conversation.