Jim
Jim

Reputation: 622

Laravel 5.3 - Conditional Image with Datatables

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.

Upvotes: 0

Views: 698

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58900

You can use columns.render option to produce alternative content for various operations.

For example:

$('#dtable').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ route('users.serverSide') }}',
    columns: [
       { data: 'id' },
       { data: 'name' },
       { data: 'email' },
       { data: 'created_at' },
       { 
          data: 'active',
          render: function(data, type, row, meta){
             if(type === 'display'){
                if(data == 1){
                   data = '<span class="fa fa-check"></span>';
                } 
             }

             return data;
          }
       }
    ]
});

Upvotes: 1

Related Questions