Trying to create a yadcf filter for a column with images - datatables

I need to create a filter on a tipical columns created with images: each field is an image with this format:
<img src='http://lab.onclud.com/psm/blackcircle.png' class='notasg'>
I've created a fiddle example here: fiddle
An explication:
there are only 2 diferents status: [assigned/not assigned] although there are 4 diferents images (black, red, yellow and green).
Only black image correspond to not assigned status. The others three ones (red, yellow and green) correspond to assigned status.
As you could see, I've tried to differentiate those status by class HTML tag in img elements (notasg/asgn).
Thanks in advance.
PD:
I'm getting data from a json, so I can't put:
<td data-search="notassigned">
directly on HTML code. As a solution, I've used createdCell (columnDefs option) as you could see on the next updated to create data-search attribute on td element fiddle.
In this one, as you could test, your previously created filter doesn't work. I've tried some solutions, but no one has worked.
Please help me again on this one. Thanks in advance.

You can make use of the datatables HTML5 data-* attributes, and then tell yadcf to rely on this dt feature with the use of html5_data
So your td will look something like
<td data-search="assigned"><img src='http://lab.onclud.com/psm/redcircle.png' class='asgn'></td>
and yadcf init will look like
var oTable = $('#example').DataTable();
yadcf.init(oTable, [
{
column_number: 0,
html5_data: 'data-search',
filter_match_mode: 'exact',
data: [{
value: 'assigned',
label: 'Assigned'
}, {
value: 'notassigned',
label: 'Not assigned'
}]
}]);
Notice that I used filter_match_mode: 'exact', because I used data-search="notassigned" and data-search="assigned", and since the assigned word included inside notassigned I had to tell yadcf to perform an exact search, this can be avoided if you will use unique search term in your data-search= attribute,
See working jsfiddle
Another solution as introduced by kthorngren from datatables forum is to use the following dt init code
var oTable = $('#example').DataTable({
columnDefs: [{
targets: 0,
render: function(data, type, full, meta) {
if (type === 'filter') {
return full[0].search('asgn') >=1 ? "assigned" : full[0].search('notasg') >= 1 ? "notassigned" : data
} else {
return data
}
}
}],
});
and yadcf init (removed html5_data)
yadcf.init(oTable, [
{
column_number: 0,
filter_match_mode: 'exact',
data: [{
value: 'assigned',
label: 'Assigned'
}, {
value: 'notassigned',
label: 'Not assigned'
}]
}
]);
third option - look here

Related

How to show icon next to value in cloumn in aurelia slickgrid/slickgrid?

I want to show en edit icon next to value in Amount column. This is because the Amount column is actually editable.But to give that as a hint to user, i want to show some edit icon next to it. How to do that in aurelia slickgrid?
Or maybe there is a way to highlight a field on hover ?
I am using aurelia slickgrid and looking if there is some option in aurelia slickgrid itself.
Go to the aurelia slickgrid example link and click on the link of example's source code
When you open it, there is a method called defineGrids
/* Define grid Options and Columns */
defineGrids() {
this.columnDefinitions1 = [
...,
...,
...,
...,
...,
{ id: 'effort-driven', name: 'Effort Driven', field: 'effortDriven', formatter: myCustomCheckmarkFormatter, type: FieldType.number, sortable: true, minWidth: 100 }
];
... rest of the code
}
The row with id effort-driven is where the icons are placed. On the other words, when you push a data collection(usually array of json object) to the table, values of the data objects with key name effort-driven are given to column with id effort-driven. Furthermore, for each passed value to the column, the method myCustomCheckmarkFormatter reformat it(for example 0 -> false or null -> not filled) and place it to the corresponding table's cell. look at the below method:
// create my custom Formatter with the Formatter type
const myCustomCheckmarkFormatter: Formatter<DataItem> = (_row, _cell, value) => {
// you can return a string of a object (of type FormatterResultObject), the 2 types are shown below
return value ? `<i class="fa fa-fire red" aria-hidden="true"></i>` : { text: '<i class="fa fa-snowflake-o" aria-hidden="true"></i>', addClasses: 'lightblue', toolTip: 'Freezing' };
};
As you can see, when the method is called, it returns an icon such as <i class="fa fa-fire red" aria-hidden="true"></i> which is placed in the table's cell.
I added an edit icon next to Amount,
{
id: "Edit",
field: "edit",
excludeFromColumnPicker: true,
excludeFromExport: true,
excludeFromQuery: true,
excludeFromGridMenu: true,
excludeFromHeaderMenu: true,
minWidth: 30,
maxWidth: 30,
formatter: Formatters.editIcon,
},
and used this custom format from ghiscoding comment:
const customEditableInputFormatter: Formatter = (_row, _cell, value, columnDef, dataContext, grid) => {
const isEditable = !!columnDef.editor;
value = (value === null || value === undefined) ? '' : value;
return isEditable ? `<div style="background-color: aliceblue">${value}</div>` : value;
};
The result is as shown in the picture.

Sorting date in datatable

I'm trying to sort dates in my datatable like DD/MM/YYYY (day, month, year) .
I was following https://datatables.net/plug-ins/sorting/ .
but all the date sorts seem to be deprecated and point to the datetime plugin: https://datatables.net/blog/2014-12-18
I don't seem to be able to get the datetime plugin working to sort. I tried the old way, with date. The initialize looks like this:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date"}],
"bInfo": true
});
Without sorting it shows the table results like this:
When I put ordering:true 2 of the 2016 dates appear somewhere else in the list (so, not in order you would expect)
With everything pointing at Moment I thought I needed to sort with that. But I'm not sure how.
I saw $.fn.dataTable.moment('DD.MM.YYYY'); somewhere, but I understood that the fn doesn't work with this newest version of datatables anymore?
Anyone knows how to sort dates?
Use date-eu sorting plugin to sort dates in the format DD/MM/YY.
Include the following JS file //cdn.datatables.net/plug-ins/1.10.11/sorting/date-eu.js and use the code below:
var historiektable = $('#dataTableHistoriek').DataTable({
"paging" : false,
"ordering" : true,
"scrollCollapse" : true,
"searching" : false,
"columnDefs" : [{"targets":3, "type":"date-eu"}],
"bInfo": true
});
The example of Gyrocode.com seems the most effective. A recent solution says to use Moments.js but it does not work in my case. date-eu is deprecated by DataTables but it works perfectly.
If you want to sort by date and time using the date format dd/MM/yyyy HH:mm, use date-euro in the same way.
var table = $('#example-table').DataTable({
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
For beginners, add the JS file date-euro to your site. Then add "columnDefs" in your code to indicate which column date-euro should be applied: targets = indicates the column containing the dates to sort, type = indicates the date-euro function to apply to the column. Finally, add "order" to apply the sort you want.
Please look into this answer for an alternate way to sort data by date.
Sample code::
<td data-search="21st November 2016 21/11/2016" data-order="1479686400">
21st November 2016
</td>
$('#dataTable').DataTable({
"order": [[10, 'desc']],
});
Thank You,
Happy Coding :)
Please refer to this pen: https://codepen.io/arnulfolg/pen/MebVgx
It uses //cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js and //cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js for sorting datatable
To sort the table by default use:
$.fn.dataTable.moment('DD/MM/YY');
$('#example').DataTable({
"order": [[ 3, "desc" ]]
});
Following Plasebo's example works, but in my case the MySQL DATE_FORMAT was sorting on month value, not entire date. My solution was to remove the DATE_FORMAT from my SQL statement.
$(document).ready(function() {
$.fn.dataTable.moment('DD/MM/YY');
$('.happyTable').DataTable({
"ordering": true,
"order": [[ 1, "desc" ]],
});
});
DATE_FORMAT(date,'%m/%d/%Y')
"2003-12-30 00:00:00"
results in "12/30/2003" but sorts on month value.
You can do your own comparator in order to keep the control of how is ordering the dates.
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"ddMmYyyy-pre": function (a) {
a = a.split('/');
if (a.length < 2) return 0;
return Date.parse(a[0] + '/' + a[1] + '/' + a[2]);
},
"ddMmYyyy-asc": function (a, b) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"ddMmYyyy-desc": function (a, b) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
As you can see in the above comparator you can choose how to parse the date depending on your data.
And in the columns definition:
"columnDefs": [
{
targets: [4], type: "ddMmYyyy"
}]
For me, using ASP.NET core 3.1 with MVC, I used a data-sort attribute on my <td> for the datatables:
<td data-sort="#(item.DueDateTime.Ticks)">
#Html.DisplayFor(modelItem => item.DueDateTime)
</td>
No plug-ins needed
See this link:
https://datatables.net/examples/advanced_init/html5-data-attributes.html
There's an ugly hack that I've used in the past especially when I couldn't quickly modify the DataTable javascript. You can add a hidden span that has the date in a sortable format.
<td><span style="visibility:hidden">2006-12-21</span>21/12/2006</td>
test
strong text
$.fn.dataTableExt.oSort['time-date-sort-pre'] = function(value) {
return Date.parse(value);
};
$.fn.dataTableExt.oSort['time-date-sort-asc'] = function(a,b) {
return a-b;
};
$.fn.dataTableExt.oSort['time-date-sort-desc'] = function(a,b) {
return b-a;
};
var table = $('#example').DataTable({
columnDefs : [
{ type: 'time-date-sort',
targets: [0],
}
],
order: [[ 0, "desc" ]]
});

Dojo DGrid RQL Search

I am working with a dgrid where I want to find a search term in my grid on two columns.
For instance, I want to see if the scientific name and commonName columns contain the string "Aca" (I want my search to be case insensitive)
My Grid definition:
var CustomGrid = declare([Grid, Pagination ]);
var gridStore = new Memory({ idProperty: 'tsn', data: null });
gridStore.queryEngine = rql.query;
grid = new CustomGrid({
store: gridStore,
columns:
[
{ field: "tsn", label: "TSN #"},
{ field: "scientificName", label: "Scientific Name"},
{ field: "commonName", label: "Common Name",},
],
autoHeight: 'true',
firstLastArrows: 'true',
pageSizeOptions: [50, 100],
}, id);
With the built in query language (I think simple query language), I was able to find the term in one column or the other, but I couldn't do a complex search that would return results for both columns.
grid.set("query", { scientificName : new RegExp(speciesKeyword, "i") });
grid.refresh()
I started reading and I think RQL can solve this problem, however, I am struggling with the syntax.
I have been looking at these pages:
http://rql-engine.eu01.aws.af.cm/
https://github.com/kriszyp/rql
And I am able to understand basic queries, however the "contains" syntax eludes me.
For instance if I had this simple data set and wanted to find the entries with scientific and common names that contain the string "Aca" I would think my contains query would look like this:
contains(scientificName,string:aca)
However, this results in no matches.
[
{
"tsn": 1,
"scientificName": "Acalypha ostryifolia",
"commonName": "Rough-pod Copperleaf",
},
{
"tsn": 2,
"scientificName": "Aegalius acadicus",
"commonName": "Northern Saw-whet Owl",
},
{
"tsn": 3,
"scientificName": "Portulaca pilosa",
"commonName": "2012-02-01",
},
{
"tsn": 4,
"scientificName": "Accipiter striatus",
"commonName": "Kiss-me-quick",
},
{
"tsn": 5,
"scientificName": "Acorus americanus",
"commonName": "American Sweetflag",
}
]
Can someone guide me in how to formulate the correct syntax? Thank you.
From what I'm briefly reading, it appears that:
contains was replaced by any and all
these are meant for array comparisons, not string comparisons
I'm not sure offhand whether RegExps can just be handed to other operations e.g. eq.
With dojo/store/Memory, you can also pass a query function which will allow you to do whatever you want, so if you wanted to compare for a match in one field or the other you could do something like this:
grid.set('query', function (item) {
var scientificRx = new RegExp(speciesKeyword, 'i');
var commonRx = new RegExp(...);
return scientificRx.test(item.scientificName) || commonRx.test(item.commonName);
});
Of course, if you want to filter only items that match both, you can do that with simple object syntax:
grid.set('query', {
scientificName: scientificRx,
commonName: commonRx
});

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.

Initially selected value from store in dijit.form.FilteringSelect

I have a dojo.data.ItemFileReadStore as follows:
var partyStore = new dojo.data.ItemFileReadStore({
id: 'partyStore',
data: {
label:'name',
items:[
{value:'APPLES', name:['Apples']},
{value:'ORANGES', name:['ORANGES']},
{value:'PEARS', name:['PEARS']}
]}
});
and a dijit.form.FilteringSelect as:
var partyList = new dijit.form.FilteringSelect({
id: "partyLookup",
name: 'partyLookup',
store: partyStore,
searchAttr: "name"}, infoDiv);
How can I make the initially selected value be Oranges?
I have tried various entries for the value in the FilteringSelect so have left it out in this example.
Your data store doesn't seem right. Try changing it to:
var partyStore = new dojo.data.ItemFileReadStore({
identifier: 'value',
items:[
{value:'APPLES', name:'Apples'},
{value:'ORANGES', name:'ORANGES'},
{value:'PEARS', name:'PEARS'}
]
});
You can then set the value of the dijit.
partyList.set('value', 'ORANGES');
I had missed off the "identifier" from the store data. It seems without the identifier being set it indexes them ie. 0,1,2,3,4...
Once I set:
identifier: 'value'
the current value of the FilteringSelect comes back as the 'value' form the data.
Sorry to answer my own question, thanks to anyone who helped or took a look.