For now you can map over $co and use number_format function to achieve this. Later if someone comes with better option you can refactor to that solution.
Format number field in yarja datatables from query
I am writing a searchable table which includes the area and population. Here is the basic query:
public function getCountryData()
{
$co = DB::table('countries')->leftJoin('country_detail','country_detail.country_id','=','countries.id')->addSelect(['countries.id','countries.name','country_detail.capital','country_detail.area','country_detail.iso3','country_detail.population','country_detail.currencyName','country_detail.phone','country_detail.continent'])->get();
return Datatables::of($co)
->addColumn('action', function($co){
$btn = '<div style="float:right">
<a href="'. route('country.edit',$co->id) .' " class="btn btn-outline-secondary btn-xs" title="edit" style="margin-right:.5em">'.getEditIcon().'</a><a href="'. route('country.show', $co->id) .'" class="btn btn-outline-secondary btn-xs" title="images" style="margin-right:.5em">'.getBinoculars().'</a>';
return $btn;
}) ->rawColumns(['action'])
->make(true);
}
All this works fine in my view except that the population field, for example, returns something like 29121286 and of course I want to format it so it is 29,121,286.
Can this be done in the query or something in Datatables itself?
@jim1506 the way I do it with DataTables is format the number on the client side. When you initialize the DataTable on your table, you could pass a callback function which will run for each row that has been created.
The function is called createdRow. And I do this:
// add this function for number formatting somewhere in your scripts, so you can reuse it
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, ',')
}
// then the DataTable
$('#your_table').DataTable({
...
createdRow: function (row, data, dataIndex) {
if (data.population !== undefined) {
// 4 here is the cell number, it starts from 0 where this number should appear
$(row).find('td:eq(4)').html(formatNumber(data.population));
}
},
pageLength: 10,
columns: [
{data: "population", name: 'population'},
... // your columns here
]
});
Hope this gives you an idea on how to do it :)
Forgot to mention that this way you don't lose the search benefit, so that the user can search using number without commas. I had a problem formatting it server side, couldn't search using the number before.
Please or to participate in this conversation.