Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jim1506's avatar

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?

0 likes
19 replies
bugsysha's avatar

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.

jim1506's avatar

Thanks but I am now certain what you mean. I have tried adding selectRaw etc

Nakov's avatar
Nakov
Best Answer
Level 73

@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.

jim1506's avatar

Thanks. I have a slight problem. I copied the function into a helper which I use but I am getting

syntax error, unexpected ')', expecting variable (T_VARIABLE)

The function as I put it in is:

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, ',');
}
Nakov's avatar

@jim1506 you know this is a JavaScript function right? So don't put it in a php helper file, but in a JavaScript one.

jim1506's avatar

I have a slight problem with the conversion. For example a figure of 29121286 is showing up as 2,12,286, 26711 is showing up as 2,711 and 2986952 is showing up as ,98,952.

I placed the script in a general javascript file which I call from the app layout:

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, ',')
}

and added this to my page in the datatables definition:

createdRow: function (row, data, dataIndex) {
                    if (data.population !== undefined) {
                        $(row).find('td:eq(4)').html(formatNumber(data.population));
                    }
                },
jim1506's avatar

If I may be so bold, I also have a field for currency formats, for example

'€'

I want them to show as (in this case) the euro symbol rather than the data

jim1506's avatar

It is refusing to let me show the code as it is showing it as the euro symbol but it is the hex code 8364 with &# before and ; after

Nakov's avatar

@jim1506 and from the same article you checked the currency formatting?

jim1506's avatar

The idea is to show the symbol as no currency amount is shown. It is a table of countries that links to a lot of information and I have a table of currencies which links so it is a case of showing the symbol only.

jim1506's avatar

The column is just a column of the symbol itself next to a column of the currency name. The database contains the hex database symbol so all I want to show is the symbol itself. In other words I want to get the string to show up as just html code.

jim1506's avatar

His site has been down for a few days, but Ok now. I just added the raw in the config and it is fine.

Thanks again

Nakov's avatar

@jim1506 you should consider marking a Best Answer if something helped you from here :) it might help others.

Please or to participate in this conversation.