Laravel-datatables: My Javascript doesnt work when it call by AddColumn on Delete Button

Created on 10 May 2017  路  11Comments  路  Source: yajra/laravel-datatables

Hey, Can someone solve my problem?

I am new on this package so i get confuse
I try to addColumn with action like Edit or Delete like this

public function table()
    {
      $employee = employee::all();

        return Datatables::of($employee)
            ->addColumn('action', function ($employee) {
              return '<center><a href="/employee/'.$employee->id.'/edit" rel="tooltip" title="Edit" class="btn btn-warning btn-simple btn-xs"><i class="fa fa-pencil"></i></a><a href="/employee/'.$employee->id.'/delete" rel="tooltip" title="Delete" class="btn btn-danger btn-simple btn-xs delete" data-name="'.$employee->name.'"><i class="fa fa-trash"></i></a></center>';
            })
            ->addColumn('position', function ($employee) {
                return $employee->position->role;
            })
            ->rawColumns(['action','position'])
            ->make(true);
    }

its work fine But javascript that contain Sweet Alert on dlete button is not working,

here my javascript

<script type="text/javascript">
    $('.delete').click(function(e) {
        e.preventDefault(); // Prevent the href from redirecting directly
        var linkURL = $(this).attr("href");
        var name = $(this).attr("data-name");
        warnBeforeRedirect(linkURL,name);
    });
    function warnBeforeRedirect(linkURL,name) {
        swal({
            title: "Are you sure?",
            text: "You will delete record with name = "+name+" !",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel it!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function(isConfirm){
            if (isConfirm) {
                console.log('done');
                swal("Deleted!", "Your record with name "+name+" has been deleted.", "success");
                window.location.href = linkURL;
            } else {
                swal("Cancelled", "Your record with name "+name+" is safe :)", "error");
            }
        });
    }
    </script>

what should i do? please help me ASAP!

question

Most helpful comment

You need to attach the scripts on drawCallback of dataTables or attach the event on the container with proper node selector. Check datatables.net official docs for js related stuffs. Thanks!

All 11 comments

once more, i got a litle problem with IF statement

how can i add this command in AddColumn?

@if ($employee->status=="Activate")
                    <a href="/employee/{{$employee->id}}/deactivate" class="btn btn-danger btn-xs" name="status">Deactivate</a>
@elseif ($employee->status=="Deactivate")
                    <a href="/employee/{{$employee->id}}/activate" class="btn btn-success btn-xs" name="status">Activate</a>
@endif

Have try like this

->addColumn('status', function ($employee) {
                return '<?php if ($employee->status=="Activate"){ ?>
                    <a href="/employee/{{$employee->id}}/deactivate" class="btn btn-danger btn-xs" name="status">Deactivate</a><?php } ?>';

but result just like this
capture

Update :
This problem Solve by myself lol , But The ## #1st still the main problem
using this code 馃憤

public function table()
    {
      $employee = employee::all();

        return Datatables::of($employee)
            ->addColumn('action', function ($employee) {
              return '<center><a href="/employee/'.$employee->id.'/edit" rel="tooltip" title="Edit" class="btn btn-warning btn-simple btn-xs"><i class="fa fa-pencil"></i></a><a href="/employee/'.$employee->id.'/delete" rel="tooltip" title="Delete" class="btn btn-danger btn-simple btn-xs delete" data-name="'.$employee->name.'"><i class="fa fa-trash"></i></a></center>';
            })
            ->addColumn('position', function ($employee) {
                return $employee->position->role;
            })
            ->addColumn('status', function ($employee) {
              if ($employee->status=="Activate") {
                return '<a href="/employee/{{$employee->id}}/deactivate" class="btn btn-danger btn-xs" name="status">Deactivate</a>';
              }elseif ($employee->status=="Deactivate") {
                return '<a href="/employee/{{$employee->id}}/activate" class="btn btn-success btn-xs" name="status">Activate</a>';
              }
            })
            ->rawColumns(['action','position','status'])
            ->make(true);
    }

Please see docs: https://yajrabox.com/docs/laravel-datatables/7.0/add-column for some ref. Thanks!

@yajra i have try this
Controller ;

```
public function table()
{
$employee = employee::all();

    return Datatables::of($employee)
        ->addColumn('intro', 'employee.action')
        ->addColumn('position', function ($employee) {
            return $employee->position->role;
        })
        ->addColumn('status', function ($employee) {
          if ($employee->status=="Activate") {
            return '<center><a href="/employee/'.$employee->id.'/deactivate" class="btn btn-danger btn-xs" name="status">Deactivate</a></center>';
          }elseif ($employee->status=="Deactivate") {
            return '<center><a href="/employee/'.$employee->id.'/activate" class="btn btn-success btn-xs" name="status">Activate</a></center>';
          }
        })
        ->rawColumns(['action','position','status'])
        ->make(true);
}

```

View ;

{{$employee->id}}

but getting error, that because ->addColumn('intro', 'employee.action') is not woking for me

this the error message 馃憤

Requested unknown parameter 'action' for row 0, column 5. For more information about this error, please see http://datatables.net/tn/4

any ideas?

When using view, the attributes are sent as own variable. Your view should look like:

ID: {{$id}}

--EDIT--
If you want to access the whole model, you need to use closure.

->addColumn('intro', function($model) {
    return view('employee.action', compact('model')->render();
})

@yajra allright, that work. but still javascript didnt call it.

even tooltip property is not working

this is what my view look like 馃憤

Action.blade.php 馃憤

<a href="/employee/{{$id}}/edit" rel="tooltip" title="Edit" class="btn btn-warning btn-simple btn-xs"><i class="fa fa-pencil"></i></a>
<a href="/employee/{{$id}}/delete" rel="tooltip" title="Delete" class="btn btn-danger btn-simple btn-xs delete" data-name="{{$name}}"><i class="fa fa-trash"></i></a>

<script type="text/javascript">
    $('.delete').click(function(e) {
    e.preventDefault(); // Prevent the href from redirecting directly
    var linkURL = $(this).attr("href");
    var name = $(this).attr("data-name");
    warnBeforeRedirect(linkURL,name);
    });
     function warnBeforeRedirect(linkURL,name) {
       swal({
           title: "Are you sure?",
           text: "You will delete record with name = "+name+" !",
           type: "warning",
           showCancelButton: true,
           confirmButtonColor: "#DD6B55",
           confirmButtonText: "Yes, delete it!",
           cancelButtonText: "No, cancel it!",
           closeOnConfirm: false,
           closeOnCancel: false
         },
        function(isConfirm){
      if (isConfirm) {
        console.log('done');
        swal("Deleted!", "Your record with name "+name+" has been deleted.", "success");
        window.location.href = linkURL;
      } else {
          swal("Cancelled", "Your record with name "+name+" is safe :)", "error");
      }
    });
      }
</script>

You need to attach the scripts on drawCallback of dataTables or attach the event on the container with proper node selector. Check datatables.net official docs for js related stuffs. Thanks!

allright thanks, its working perfectly just like i want. @yajra.

close

@yajra did you know why this tooltips didnt working?

Before using Plugins =

1

After using Plugin =

2

im using REL, not class for tooltips.

You also need to reinitialize the tooltip plugin on drawCallback like:

dataTable.on('draw.dt', function () {
        // fix bootstrap tooltip plugin.
        $('.tooltip.fade.top.in').hide();
        $('[data-toggle=tooltip]').tooltip({container: 'body'});
    });

its working, thanks.

im using this. @yajra

drawCallback : function( settings ) { $("[rel=tooltip]").tooltip(); }

thanks, also solved my problem.

drawCallback: function(settings){
            console.log(settings);
            $('.btnValidate').click(function(){
                var idAcara = $(this).data('acara');
                console.log(idAcara);

                swal({
                    title: "Acc Proposal?",
                    text: "Ketika sudah di ACC, tidak dapat dikembalikan kembali!",
                    icon: "warning",
                    buttons: true,
                    dangerMode: false,
                  })
                  .then((willDelete) => {
                    if (willDelete) {
                        $.ajax({
                            method: 'post',
                            url: "/accproposal",
                            data: {
                                id: idAcara,
                                _token: $('meta[name="csrf-token"]').attr('content')
                            }
                        })
                        .done(function(resp){
                            console.info("SUKSES");
                            console.info(resp);
                            swal("Telah di acc", {
                                icon: "success",
                            });

                            setTimeout(() => {
                                location.reload();
                            }, 2000);          
                        })
                        .fail(function(resp){
                            console.error(resp);
                            console.log("GAGAL UPDATE");
                        });

                    } else {
                      swal("Proses ACC proposal dibatalkan");
                    }
                  });
            });

Was this page helpful?
0 / 5 - 0 ratings

Related issues

faisalhilmi picture faisalhilmi  路  18Comments

marioene picture marioene  路  22Comments

Yahav picture Yahav  路  16Comments

phainv picture phainv  路  16Comments

mithleshjs picture mithleshjs  路  16Comments