How can I implement new line in a column (DataTables) - datatables

I have an SQL query that grabs some data (language column in dbtable table). The query uses GROUP_CONCAT, so one cell has several results, e.g.
"Ajax, jQuery, HTML, CSS".
What I want to do is to show the result in new lines, like:
"Ajax
jQuery
HTML
CSS"
How can I do that?
I tried to make it by changing "columns": [{ "data": "id" }, { "data": "languages" }... but it didn't work.
I also tried to fix it by adding "< br >" in query as a Separator, but didn't work.
Thank you!

You can use columns.render function for the column like this:
var table = $('#example').DataTable({
columns: [
null,
null,
{
"render": function(data, type, row){
return data.split(", ").join("<br/>");
}
}
]
});
Working example.
Hope that helps and that I've understood your problem.

To implement new line in a column for DataTables
Assume that there are 7 columns in a row and the 4th column has the data
"Ajax, jQuery, HTML, CSS"
so the 3 columns before and 3 columns after has to be made null in the code
$('#example').DataTable({
columns: [
null, null, null,
{
"render": function(data, type, row){
return data.split(", ").join("<br/>");
}
},
null, null, null
]
});

#annoyingmouse answer is perfect taking into account the question description!
Just an extra answer following "strictly" the question (as it is) which says:
How can I implement new line in a column (DataTables)
You have just to add a wrap class on the <table> tag. Tada! Each column text will be wrapped when reaching its predefined width.

Related

Add exception to natural sorting in datatables

Is there a way to add exceptions to the natural ordering plugin, so that it ignores things like c. , [, ], ? ?
This is an example of my data:
161?
1604
[1563]
c. 1476
I'd like the sorted asc. output to be:
c. 1476
[1563]
1604
161?
Right now what I get is all the numbers first, and the strings beginning with [ afterwards.
My initialisation code:
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/1.10.24/sorting/natural.js"></script>
$('#sourcesList').DataTable({
"paging": false,
"columnDefs": [
{ type: 'natural-nohmtl', targets: '_all' }
],
[...]
PS: this is my data in the wild.
The natural sorting option takes care of certain types of numeric data which you can reasonably expect to encounter in the "real world" - such as numbers with different thousands separators, or with currency symbols of different types in different positions - or "1st", "2nd" "3rd" and so on. Don't quote me on these exact examples, as I have not looked at that add-on in detail. But that is the overall idea.
Items such as question-marks - I would not expect that add-on to handle those. Items in square brackets - same thing.
Given your clarification in a comment, I think you do not need or want this add-on.
Instead you can use a column renderer with DataTables' ability to store different versions of a value - for display, sorting, and filtering.
var dataSet = [ ["161?"], ["1604"], ["[1563]"], ["c. 1476"] ];
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columnDefs: [ {
type: "natural-nohmtl",
targets: [ 0 ],
title: "My Data",
"render": function ( data, type, row, meta ) {
if ( type === 'sort' ) {
//return parseInt(data.replace(/\D/g, '')); // numbers as numbers
return data.replace(/\D/g, ''); // numbers as strings
} else {
return data;
}
}
} ]
} );
} );
This saves a version of each value with all non-digits stripped from the value, using replace(/\D/g, ''). This altered version of the data is stored as the value which will be used when sorting. The unaltered version is what the user will see.
My result:
This is the case where numbers are treated as text.
You can uncomment the commented-out return statement to get numbers as numbers.
However...
This crude approach of stripping non-digits from the data meets the narrow example from your question, but it may not be sufficient for all the data you are expecting to handle. So, you may need to refine the "replace" logic.
But the render function should meet your needs, more generally.

How to display two column values in a single ag-grid cell?

I have a record of First_Name and Second_Name stored in MySql DB. Currently I am displaying it in 2 different columns of Ag-Grid. I need those data to be combined together as Name and to be displayed in Ag-Grid's single column. Please help!
I am using Vue.Js
You should use a valueGetter in your columnDef like this -
{
headerName: 'Name',
colId: 'name',
valueGetter: function(params) {
return params.data.First_Name + " " + params.data.Second_Name;
},
},
Example from docs here
The ans stated by Pratik is right. Maybe you can use arrow functions for valueGetter so that the code looks more concise and simplify function scoping.
{
headerName: 'Name',
valueGetter: params => {
return ${params.data.First_Name} ${params.data.Second_Name};
},
},

Filter other columns based on first columns

I'm using jquery data tables and I'm assigning an array of values to the initialization of the data table. The table basically looks like this.
based on an an radio button I would like to limit the items that are display in the table and the items that are searched in the table.
For my example it would be based on the "Chart column". I want to limit the table to only show the items that are based on chart "D" or Chart "S". Here is how I'm initializing the table.
if (!$.fn.DataTable.isDataTable( '#fundLookUptbl' ) ) {
fundTable = $('#fundLookUptbl').DataTable( {
data: funds,
columns: [
{ "mData": "chart" },
{ "mData": "fund" },
{ "mData": "orgDefault" },
{ "mData": "progDefault" }
]
} );
var filteredData = fundTable
.columns( [0, 1] )
.data()
.eq( 0 )
.filter( function ( value, index ) {
return value = 'D' ? true : false;
} );
}
This is obviously not working, and the filterData variable is a lousy attempt on trying to make it work. I'm having a hard time understanding the API's. So the question is , How can initialize the table to only show the items that are based on a given chart. I know that I can remove the items of the array but i don't want to do that since I would simple like to be able to switch between chart "D" and "S" but still continue to search through the other columns.
I believe that filtering the column would solve your problem.
table.column(0).search('Bruno').draw()
So you could just filter the column when the radio button selection change
Here is a fiddle example
I´m not sure to be understanding what you want to do but here are some options:
One way is selecting by default value example "s". You can use a dropdown is easier to handled .Then select with jQuery the dafault value "s" on that dropdown and add a function
$("#DropdownId").change(function () {
var chart=$("#DropdownId").val();
});
$.ajax({
url: "url")",//url to reload page with new value
type: "POST",
data: {chart:chart},
success: function (data) {
}
});
});
on this way the filter is on backend. If you want to do something on the row depending of a column value you shoud to add something like this
"fnRowCallback": function (nRow, mData, iDisplayIndex, iDisplayIndexFull) {
if (mData["chart"] =="s") {
return nRow;
}
},
Datatables: custom function inside of fnRowCallback.
Good luck
fundTable.order( [0, 'asc'] );
Try that or look at this particular page for reference:
https://datatables.net/reference/api/order%28%29
Basically orders in pair of columnIndex in either asc(ending) or desc(ending) order.

datatables column header reflect value used to sort

I've got datatables set up with about 10 columns, two of which do customized filtering when clicking the column headers.
I'd like to change the column header to reflect which filter is currently active.
To do it, I think I'll need to set up fnDrawCallback and look at the values returned by table.fnSettings()
My current code, trimmed to its essentials for this question:
var table = $('#units').dataTable({
"aaSorting": (popSearch) ? [[8,"asc"]] : [],
"aoColumns":[{ "bSortable": false },
{ "bSortable": false },
{ "asSorting": [ "", "on", "off", "occ", "none" ] },
null,
null,
{ "asSorting": [ "", "revised", "new" ] },
null,
null,
{ "bSortable": false },
{ "bSortable": false }
],
"oSearch": {"sSearch": searchString},
"sAjaxSource": "/system/units/data.php?1.4.3"
},
"fnDrawCallback": function() {
/* tweak column headers according to the asSorting value */
}
});
The asSorting arrays in the aoColumns array show the list of different filters that may be applied to the data being fed to datatables. If the third column header (Status) is clicked, I'd like its text to match what data was sent, (falling back to "status" if the empty string was sent). The filtering works, fine; I just want the header to reflect the applied filter.
In Datatables fnDrawCallback function, how do I know what values were sent for column sorting?
To enable which Column is being Sorted, and visually see it, all you should have to do is add the
"bSortClasses": true,
To your Data Tables Script. Such as:
"aaSorting": (popSearch) ? [[8,"asc"]] : [],
"bSortClasses": true,
...
You should see which column, is being used as the sorter. :)

View pictures or images inside Jquery DataTable

May I know if it is possible to put pictures or images into the rows of DataTables (http://datatables.net/) and how does one goes in doing it?
yes, simple way (Jquery Datatable)
<script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax":{
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/Home/AjaxGetJsonData",
"type": "GET"
},
"columns": [
{ "data": "Name", "orderable" : true },
{ "data": "Age", "orderable": false },
{ "data": "DoB", "orderable": true },
{
"render": function (data, type, JsonResultRow, meta) {
return '<img src="Content/Images/'+JsonResultRow.ImageSrcDB+'">';
}
}
],
"order": [[0, "asc"]]
});
});
</script>
[edit: note that the following code and explanation uses a previous DataTables API (1.9 and below?); it translates easily into the current API (in most cases, just ditch the Hungarian notation ("fnRowCallback" just becomes "rowCallback" for example) but I have not done so yet. The backwards compatibility is still in place I believe, but you should look for the newer conventions where possible]
Original reply follows:
What Daniel says is true, but doesn't necessarily say how it's done. And there are many ways. Here are the main ones:
1) The data source (server or otherwise) provides a complete image tag as part of the data set. Don't forget to escape any characters that need escaping for valid JSON
2) The data source provides one or more fields with the information required. For example, a field called "image link" just has the Images/PictureName.png part. Then in fnRowCallback you use this data to create an image tag.
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var imgLink = aData['imageLink']; // if your JSON is 3D
// var imgLink = aData[4]; // where 4 is the zero-origin column for 2D
var imgTag = '<img src="' + imgLink + '"/>';
$('td:eq(4)', nRow).html(imgTag); // where 4 is the zero-origin visible column in the HTML
return nRow;
}
3) Similar to above, but instead of adding a whole tag, you just update a class that has the image as a background. You would do this for images that are repeated elements rather than one-off or unique pieces of data.
You mean an image inside a column of the table?
Yes, just place an html image tag
like this
<img src="Images/PictureName.png">
instead of putting data (some string) into a column just put the above html tag....
Asp.net core DataTables
The following code retrieve the image from a folder in WWWroot and the path in the DB field ImagePath
{
"data": "ImagePath",
"render": function (data) {
return '<img src="' + data + '" class="avatar" width="50" height="50"/>';
}
}
In case the Name of the picturefile is put together out of one or more informations in the table, like in my case:
src="/images/' + Nummer + Belegnummer + '.jpg"
you can make it that way:
var table = $('#Table').DataTable({
columnDefs: [
{
targets: 0,
render: getImg
}
]
});
function getImg(data, row, full) {
var Nummer = full[1];
var Belegnummer = full[4];
return '<img src="/images/' + Nummer + Belegnummer + '.jpg"/>';}
The picture is in the first column, so Targets = 0 and gets the Information from the same row.
It is necessary to add the parameters data and row.
It is not necessary to outsource it into a seperate function, here getImg, but it makes it easier to debug.