here are a few ways you can use custom functions with `$.fn.dataTable.render.text()` and `$.fn.dataTable.render.number()` in Yajra DataTables:
Using `$.fn.dataTable.render.text()`
To combine `$.fn.dataTable.render.text()` with a custom function, you can do the following:
php
$textRenderer = $.fn.dataTable.render.text().display;
return DataTables::eloquent(User::select())
->addColumn('name', function($user) use ($textRenderer) {
return $textRenderer($user->name);
})
->toJson();
This will use the `$.fn.dataTable.render.text().display` function to escape the HTML in the `name` column, while allowing you to add custom logic within the closure.
Using `$.fn.dataTable.render.number()`
Similarly, you can combine `$.fn.dataTable.render.number()` with a custom function:
php
$numberRenderer = $.fn.dataTable.render.number(',', '.', 2, '$');
return DataTables::eloquent(User::select())
->addColumn('salary', function($user) use ($numberRenderer) {
return $numberRenderer($user->salary);
})
->toJson();
This will use the `$.fn.dataTable.render.number()` function to format the `salary` column, while allowing you to add custom logic within the closure.
Using `columnDefs`
Alternatively, you can use the `columnDefs` option to apply the renderers to specific columns without having to redefine all the columns:
php
return DataTables::of(User::select())
->addColumn('name', function($user) {
return $user->name;
})
->addColumn('salary', function($user) {
return $user->salary;
})
->columnDefs([
[
'targets' => 0,
'render' => $.fn.dataTable.render.text().display
],
[
'targets' => 1,
'render' => $.fn.dataTable.render.number(',', '.', 2, '$')
]
])
->toJson();
This will apply the `$.fn.dataTable.render.text().display` function to the `name` column and the `$.fn.dataTable.render.number()` function to the `salary` column, without having to redefine all the columns.
The key points are:
1. Use the `$.fn.dataTable.render.text().display` function to escape HTML in a column.
2. Use the `$.fn.dataTable.render.number()` function to format a numeric column.
3. Combine these renderers with custom functions within the column definition closures.
4. Use the `columnDefs` option to apply the renderers to specific columns without redefining all columns.
[1] https://datatables3.rssing.com/chan-5199417/article41149.html
[2] https://datatables.net/forums/discussion/50733/fn-datatable-render-text-combine-with-render-function-data-type-row
[3] https://datatables.net/forums/discussion/45886/how-to-use-fn-datatable-render-text-on-a-columns-without-defining-all-columns
[4] https://datatables3.rssing.com/chan-5199417/all_p1714.html
[5] https://datatables.net/forums/discussion/77449/how-to-use-a-second-render-function-alongside-a-datatable-render-text-render-anti-xss-security