jim1506's avatar

Datatables and conditional images - 5.3

I have a simple table showing the users table, to which I have added an 'active' field with a value of 1 for active and 0 for inactive.

I have the following view (the jquery and datatables and pulled in the app view):

@extends('layouts.app')
@section('content')

<div class="panel panel-default" style="padding-left: 2em; padding-right: 2em">
  <div class="panel-heading">Users</div>
  <div class="panel-body"> 
     <table class="datatable" id="dtable" width="90%" align="center">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Created at</th>
            <th>active</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
  </div>
</div>

  <script>
    $(document).ready(function(){
      $('#dtable').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route('users.serverSide') }}'
        });
    });
  </script>
@endsection

In web.php I have the following method to get the data:

Route::get('/users/serverSide', [
    'as'   => 'users.serverSide',
    'uses' => function () {
        $users = App\User::select(['id', 'name', 'email', 'created_at', 'active']);
 
        return Datatables::of($users)->make();
    }
]);

All this works fine, but I would like to replace the 1 or 0 in the active table with either a tick or a cross, using either a site icon or Fontawesome.

Anyone point me in the right direction please? I know I could set up a view in mySQL but they tend to be slow.

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

something like this

    $('#dtable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ route('users.serverSide') }}',
        "columnDefs": [ {
            "targets": 4,   // choose the correct column
            "render": function ( data, type, full, meta ) {
                if(data) {
                    return '<i class="fa fa-check"> </i>';
                }
                return '<i class="fa fa-times"> </i>';
        }]
    });

https://datatables.net/reference/option/columns.render

https://datatables.net/examples/advanced_init/column_render.html

jim1506's avatar

With a little bit of tinkering I got red for the crosses and green for the ticks:

 $('#dtable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ route('users.serverSide') }}',
        "columnDefs": [ {
            "targets": 4,   // choose the correct column
            "render": function ( data, type, full, meta ) {
                if(data == 1) 
                { return '<span style="color: green"><i class="fa fa-check"> </i></span>';} 
                    else 
                { return '<span style="color: red"><i class="fa fa-times"> </i></span>'; } }
        } ]
    });  

Please or to participate in this conversation.