I have a laravel project that implements datatables to display data. I want to use some labels to format some columns on the table.
The problem now is having a second switch statement , the first one is working fine and the formatting is showing up fine.
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'role_id', name: 'role_id' },
{ data: 'phone', name: 'phone' },
{ data: 'email', name: 'email' },
{ data: 'status', name: 'status' },
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action' }
],
columnDefs : [
{ targets : [5],
render : function (data, type, row) {
switch(data) {
case 0 : return '<span class="label label-danger">Inactive</span>';
break;
case 1 : return '<span class="label label-primary">Active</span>';
break;
case 2 : return '<span class="label label-danger">Suspended</span>';
break;
}
}
},
I want to have column 2 and 5 formatted with labels, how to achieve this ?
I managed to sort it out.
One my initial call from the controller I had the to use the default value from the table then change the datatable code to call the table name as is.
from this
return $user->role['name'];
})
to this
return $user->role_id;
})
then I had to call my columnDefs on the index view like this
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'role_id', name: 'role_id' },
{ data: 'phone', name: 'phone' },
{ data: 'email', name: 'email' },
{ data: 'status', name: 'status' },
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action' }
],
columnDefs : [
{ targets : [5],
render : function (data, type, row) {
switch(data) {
case 0 : return '<span class="label label-danger">Inactive</span>';
break;
case 1 : return '<span class="label label-primary">Active</span>';
break;
case 2 : return '<span class="label label-danger">Suspended</span>';
break;
}
}
},
{ targets : [2],
render : function (data, type, row) {
switch(data) {
case 1 : return '<span class="label label-danger"> SuperAdmin </span>';
break;
case 2 : return '<span class="label label-primary"> Admin </span>';
break;
case 3 : return '<span class="label label-success"> Support </span>';
break;
case 4 : return '<span class="label label-info">Customer Admin </span>';
break;
case 5 : return '<span class="label label-dark"> Customer Support </span>';
break;
case 6 : return '<span class="label label-yellow">Customer Technician </span>';
break;
case 7 : return '<span class="label label-purple"> App User </span>';
break;
}
}
}
],
Related
I have implemented yajra datatables successfully for all reviews. One review can have 3 statuses: Approved, Pending, Blocked.
I have a column on datatables which is called Status and I want to sort column by status. By default the status is being ranged as per Approved and Declined but not for Pending.
Is there any way so I can sort this column by routing on this 3 statuses?
I'm sure that there is some editColumn or filterColumn method for my question but I'm not finding it any where.
Any way for #andrewjames pleasure I'm adding some non necessary code here:
public function indexDataService()
{
$reviews = DB::table('reviews')
->join('users', 'reviews.user_id', '=', 'users.id')
->join('statuses', 'reviews.status_id', '=', 'statuses.id')
->join('products', 'reviews.product_id', 'products.id')
->join('categories', 'reviews.category_id', 'categories.id')
->select([
'reviews.*',
'reviews.created_at AS created_at',
'statuses.title AS status',
DB::raw('CONCAT(users.first_name, " ", users.last_name) AS full_name'),
'products.title',
DB::raw('categories.title as category'),
])
->where('reviews.deleted_at', '=', NULL);
return Datatables::of($reviews)
->addColumn('action', function($review){
return view('admin/reviews/reviews_actions', compact('review'));
})
->editColumn('created_at', function ($review) {
$formatedDate = Carbon::createFromFormat('Y-m-d H:i:s', $review->created_at)->format('d-m-Y');
return $formatedDate;
})
->filterColumn('full_name', function ($query, $keyword) {
$keywords = trim($keyword);
$query->whereRaw("CONCAT(first_name, last_name) like ?", ["%{$keywords}%"]);
})
->filterColumn('category', function ($query, $keyword) {
$keywords = trim($keyword);
$query->whereRaw("categories.title like ?", ["%{$keywords}%"]);
})
->make(true);
}
On blade:
<script>
$('#category-reviews-table tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'" />' );
} );
$(function() {
$('#category-reviews-table').DataTable({
"sDom":"ltipr",
processing: false,
serverSide: true,
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Italian.json"
},
ajax: '{{ route('admin.reviews.data') }}',
columnDefs: [
{"className": "dt-center", "targets": "_all"},
{
targets: [1],
render: function ( data, type, row ) {
return type === 'display' && data.length > 10 ?
data.substr( 0, 20 ) +'…' :
data;
}
}
],
columns: [
{ data: 'full_name', name: 'full_name' },
{ data: 'title', name: 'products.title' },
{ data: 'category', name: 'category'},
{ data: 'no_yes', name: 'reviews.no_yes', searchable:false },
{ data: 'status', name: 'status', searchable:false,
render: function( data, type, full, meta ) {
if (data === 'In attessa') {
return "<span class=\"badge badge-warning\">In attessa</span>";
} else if (data === 'Approvata') {
return "<span class=\"badge badge-success\">Approvata</span>";
} else if (data === 'Rifiutata') {
return "<span class=\"badge badge-danger\">Rifiutata</span>";
}
}
},
{ data: 'created_at', name: 'reviews.created_at', searchable:false },
{ data: 'action', name: 'action', orderable: false, searchable:false }
],
initComplete: function () {
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
},
});
});
Can anyone give me some example how to achieve it?
i have problem with yajra datatables to make row group in server side. I want row group show all employee in companies.name. and my current code like this:
public function index(DataTablesBuilderService $builder)
{
$columns = [
'name' => [
'title' => "company",
'name' => 'companies.name'
];
$dataTables = $builder
->setUrl(route('api.employee_details.data_tables', request()->all()))
->withIndex()
->setColumns($columns);
return view('employee_details.index')->with([
'dataTables' => $dataTables,
]);
}
and in blade i just call datatable like this
{!! $dataTables->table(['class' => 'table table-bordered','style' => 'width:100%', 'cellspacing' => '0']) !!}
and the script like this
{!! $dataTables->scripts() !!}
If i following the tutorial on https://datatables.yajrabox.com/eloquent/master, its possible to make row group but i dont know how to implement in server side. But is so different with my code in blade. Tutorial call datatable like this.
var template = Handlebars.compile($("#details-template").html());
var table = $('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'https://datatables.yajrabox.com/eloquent/master-data',
columns: [
{
"className": 'details-control',
"orderable": false,
"searchable": false,
"data": null,
"defaultContent": ''
},
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'}
],
order: [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#users-table tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
var tableId = 'posts-' + row.data().id;
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(template(row.data())).show();
initTable(tableId, row.data());
tr.addClass('shown');
tr.next().find('td').addClass('no-padding bg-gray');
}
});
function initTable(tableId, data) {
$('#' + tableId).DataTable({
processing: true,
serverSide: true,
ajax: data.details_url,
columns: [
{ data: 'id', name: 'id' },
{ data: 'title', name: 'title' }
]
})
}
and the result like this and i expected like this to but in datatables server side
Thank you if you can help to help me and explain how to solve the problem code
Injecting this in your DataTable options may help you (I've tried and it's working in my case)
$(selector).DataTable({
startRender: function (rows, group) {
var grpName = rows.data().pluck('company')
.reduce(function (a, b) {
return (b === null ? '' : b);
}, '');
return $('<tr/>')
.append('<td colspan="' + columns.length + '" class="text-left"><span class="ml-10px">' + grpName + '</span></td>');
},
endRender: null,
dataSrc: 'company'
})
I'm currently using datatabels 7.0 and Laravel 5.4
data in my grid is showing correctly but when I want to search on nested relationship column I got below error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'course_semester.semester.name' in 'where clause' (SQL: select count(*) as aggregate from (select '1' as `row_count` from `videos` where LOWER(`videos`.`id`) LIKE %%te%% and LOWER(`videos`.`name`) LIKE %%te%% and LOWER(`course_semester`.`semester`.`name`) LIKE %%te%%) count_row_table)
Here is my code
Controller
$videos = Video::with(['course_semester' => function ($query) {
return $query->with('course', 'semester');
}])->select('videos.*');
return Datatables::of($videos)
->addColumn('check', '<input type="checkbox" name="selected-videos" value="{{$id}}">')
->escapeColumns([])
->make(true);
Javascript
columns: [
{ data: 'check' , name: 'check',orderable: false, searchable: false },
{ data: 'id', name: 'videos.id' },
{ data: 'name', name: 'videos.name' },
{ data: 'course_semester.semester.name', name: 'course_semester.semester.name'},
{ data: 'course_semester.course.name', name: 'course_semester.course.name'},
{ data: 'status', name: 'videos.status' },
{ data: 'comment', name: 'videos.comment' },
{ data: 'video_date', name: 'videos.video_date' },
]
Can anyone help me and notice my problem?
Thanks in advance.
Because of using select() here, you do not load the relationship. Also, use dot syntax for nested eager loading:
$videos = Video::with(['course_semester', 'course_semester.course'])
1- dataTable function
public function dataTable($query)
{
return datatables()
->eloquent($query)
->addColumn('BulkSelection', function ($category)
{
->addColumn('company', function ($category)
{
return $category->company ? $category->company->name : 'No Company';
})
->rawColumns(['action', 'company', 'createdAt','BulkSelection']);
}
2- query function
public function query(Category $model)
{
return $model->with('company:id,name')->select('categories.*')->newQuery();
}
3- getColumns function
$getCols = [
'id',
'name',
'company'=> [
'data'=>'company',
'name'=>'company.name'
],
'createdAt' => [
'name'=>'created_at',
'searchable' => false
],
'action' => [
'exportable' => false,
'searchable'=>false,
'orderable' => false
]
];
return $getCols;
If you just need to load the data from relation tables, use the below code
$videos = Video::with('course_semester','course', 'semester')->select('videos.*');
return Datatables::eloquent($videos)
->addColumn('check', function(Video $v){
return '<input type="checkbox" name="selected-videos" value="{{$v->id}}">'
})
->rawColumns(['check'])
->make(true);
And in script, you can call relation values as ,
{data: 'course_semester.id'},
{data: 'course.name'},
{data: 'semester.name'},
$getCols = [
'title',
'Images' => [
'name'=>'images_count',
'data'=>'images_count',
'searchable'=>false
],
'price' => ['name'=>'start_price', 'data'=>'start_price'],
'reserve_price',
'Category' => [
'data'=>'show_category',
'name'=>'categories.name',
'searchable'=>false
],
'created_by' => [
'name'=>'user.name',
],
'createdAt' => [
'name'=>'created_at',
'searchable' => false
],
'action' => [
'exportable' => false,
'searchable'=>false,
'orderable' => false
]
I am creating a datatable using Laravel's Yajra plugin. I am using the query builder form.(Like this Click here)
I wanna add buttons CSV,PDF to the datatable.
I know as per the documentation it can be done Like this
The problem is I have already done using query builder. Now I cannot change my code.
Kindly help me.
My jquery code is as follows:
<script type="text/javascript">
$(document).ready(function(){
$('body').addClass('sidebar-collapse');
var cat = "{{$cat}}";
$('#unreconcil_datatable').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('get_datatable',array('cat'=>$cat)) !!}',
columns: [
{ data: 'unrelines_uniq_num', name: 'unrelines_uniq_num' },
{ data: 'unrelines_bank_accno', name: 'unrelines_bank_accno' },
{ data:'unrelines_rficreated',name:'unrelines_rficreated'},
{ data: 'unrelines_roicreated', name: 'unrelines_roicreated' },
{ data: 'unrelines_bank_name', name: 'unrelines_bank_name' },
{ data: 'unrelines_line_number', name: 'unrelines_line_number' },
{ data: 'unrelines_state_date', name: 'unrelines_state_date' },
{ data: 'unrelines_trans_date', name: 'unrelines_trans_date' },
{ data: 'unrelines_trans_amount', name: 'unrelines_trans_amount' },
{ data: 'unrelines_unrec_amt', name: 'unrelines_unrec_amt' },
{ data: 'unrelines_desc', name: 'unrelines_desc' },
{ data: 'unrelines_variance', name: 'unrelines_variance' },
{ data: 'unrelines_cstatus', name: 'unrelines_cstatus' },
{ data: 'unrelines_assigned', name: 'unrelines_assigned' },
{ data: 'unrelines_created_date', name: 'unrelines_created_date' },
{data: 'tat', name: 'tat', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
My controller method is as follows:
public function getdatatable($cat){
$list = AvailableStatementLines::select([DB::raw(" '$cat' AS cat"),'unrelines_id','unrelines_uniq_num','unrelines_bank_accno','unrelines_rficreated','unrelines_roicreated','unrelines_bank_name','unrelines_line_number','unrelines_state_date','unrelines_trans_date','unrelines_trans_amount','unrelines_unrec_amt','unrelines_desc','unrelines_variance','unrelines_cstatus','unrelines_assigned','unrelines_created_date','unrelines_trans_type','unrelines_currency','unrelines_created_by_name','unrelines_ustatus',DB::raw("IF(unrelines_cstatus='closed', '',
ROUND(ABS(TIMESTAMPDIFF(MINUTE, date(unrelines_lastupdate), curdate()))/1440 - ABS(DATEDIFF(ADDDATE(curdate(), INTERVAL 1 -DAYOFWEEK(curdate()) DAY), ADDDATE(date(unrelines_lastupdate), INTERVAL 1 -DAYOFWEEK(date(unrelines_lastupdate)) DAY))) / 7 * 2 - (DAYOFWEEK(IF(date(unrelines_lastupdate) < curdate(), date(unrelines_lastupdate), curdate())) = 1) - (DAYOFWEEK(IF(date(unrelines_lastupdate) > curdate(), date(unrelines_lastupdate), curdate())) = 7),0)
) AS tat")])->where('unrelines_ucountry',Session::get('country'))->where('unrelines_display',1);
switch($cat){
case 'rfi':
$list1 = $list->where('unrelines_cstatus','Assigned');
break;
case 'roi':
$list1 = $list->where('unrelines_cstatus','Solution Provided');
break;
case 'closed':
$list1 = $list->where('unrelines_cstatus','Closed');
break;
default:
$list1 = $list->whereNotIn('unrelines_cstatus',['Closed','Assigned','Solution Provided']);
break;
}
return Datatables::of($list1)
->addColumn('unrelines_uniq_num',function($list1){
return "<input type='checkbox' class='uniqnums' name='uniquenum[]' value='".$list1->unrelines_id."'>".$list1->unrelines_uniq_num;
})
->addColumn('action',function($list1){
return "<button type='button' class='btn btn-xs btn-info viewLine' category=".$list1->cat." unrelines=".$list1->unrelines_id.">View</button>";
})
->setRowClass(function ($list1) {
return $list1->tat > 7 ? 'orange' : ($list1->tat > 5 ? 'red' : ' ');
})
->make(true);
}
You should apply this method in your controller.
public function html()
{
return $this->builder()
->columns([
'id',
'name',
'email',
'created_at',
'updated_at',
])
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'pdf', 'print', 'reset', 'reload'],
]);
}
This is the bill_info table, for which i need to serialized row no like 1 2 . . . . . . . . . . . . .n
There is data list returned, how I can get serial_no custom field in datatable list view.
$data = BillInfo::get(['bill_info.*']);
return Datatables::of($data)
->removeColumn('id')
->make(true);
If you are using yajra laravel datatables
Just add ->addIndexColumn()
return DataTables::of($data)
->addIndexColumn()
->make(true);
In your javascript, you can set the first row as a serial number like this
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
{ data: 'name', name: 'name' },
{ data: 'action', name: 'action' }
]
use DT_Row_Index instead of DT_RowIndex for older yajra datatable version
When using Yajra Laravel datatables
return DataTables::of($result)
->addIndexColumn()
->make(true);
"columns": [
{
"data": 'DT_RowIndex',
orderable: false,
searchable: false
},
]
Set the variable rownum at the beginning of your query. Then set the increment process in your query.
DB::statement(DB::raw('set #rownum=0'));
$data = BillInfo::get(['bill_info.*',
DB::raw('#rownum := #rownum + 1 AS rownum')]);
return Datatables::of($data)
->removeColumn('id')
->make(true);
Here you can get rownum as serial no of the given records [1 . . . 8].
In Laravel Yajra Datatables v9.x as Service Implementation, I add this in getColumns function and works well in sorting, searching, and page changing.
'id' => ['title' => 'N.', 'orderable' => false, 'searchable' => false, 'render' => function() {
return 'function(data,type,fullData,meta){return meta.settings._iDisplayStart+meta.row+1;}';
}],
You can see my code :
<table id="datatable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sl No</th>
<th>Invoice No</th>
<th>Customer</th>
<th>Total Price</th>
<th>Paid</th>
<th>Due</th>
<th>Discount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And the script part:
<script type="text/javascript">
$(function() {
var i = 1;
var table = $('#datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('collections') }}",
columns: [{
"render": function() {
return i++;
}
},
{
data: 'issue_no',
name: 'issue_no'
},
{
data: 'customer_name',
name: 'customer_name'
},
{
data: 'total_order_price',
name: 'total_order_price'
},
{
data: 'paid_amount',
name: 'paid_amount'
},
{
data: 'due_amount',
name: 'due_amount'
},
{
data: 'discount_amount',
name: 'discount_amount'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
}
],
createdRow: function ( row, data, index ) {
if (data['due_amount'] > 0) {
$('td', row).eq(4).css('background-color', '#f4511e','color','#ffffff');
$('td', row).eq(4).css('color','#ffffff');
} else {
}
$('td', row).eq(3).addClass('text-right');
$('td', row).eq(4).addClass('text-right');
$('td', row).eq(5).addClass('text-right');
$('td', row).eq(6).addClass('text-right');
}
});
});
</script>
In the rendering part, you can add the auto-increment field
{
"render": function() {
return i++;
}
},
simple using render function script on yajra datatable, this is my code:
protected function getColumns()
{
return [
Column::make('row_number')
->title('#')
->render('meta.row + meta.settings._iDisplayStart + 1;')
->width(50)
->orderable(false),
];
}