Filter other columns based on first columns - datatables

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.

Related

How to use gt/le operator in aurelia slickgrid with Odata

I want to send my own operator in odata request and not use the aurelia slickgrid inbuilt "eq" operator.
This is my column definition
{
id: 'LockoutEndDateUtc', name: 'Status', field: 'LockoutEndDateUtc', minWidth: 85, maxWidth: 95,
type: FieldType.boolean,
sortable: true,
formatter: Formatters.multiple,
params: { formatters: [this.StatusFormatter, Formatters.checkmark] },
filterable: true,
filter: {
collection: [
{ value: 'le ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'True' },
{ value: 'gt ' + (() => {const dt = new Date(); return dt.toISOString().split('.')[0] + "Z";})(), label: 'False' }
], //['', 'True', 'False'],
model: Filters.singleSelect,//multipleSelect//singleSelect,
}
}
This is the UI
This is how the request filter looks like..
$filter=(LockoutEndDateUtc%20eq%20le%202022-06-28T12%3A59%3A25Z)
If i remove %20eq from the above request, everything else works. So my question is how to i remove %20eq. Or how do i send my own gt, le in the request.
You can't really do that on a boolean filter (you could however do it on a date filter with operator) and I don't think I've added any ways to provide a custom filter search the way you want to do it, but since you're using OData, you have a bit more control and you could change the query string yourself. To be clear, it's not at all recommended to change the OData query string, it's a last solution trick and at your own risk, but for your use case it might be the only way to achieve what you want.
prepareGrid() {
this.gridOptions = {
// ...
backendServiceApi: {
service: new GridOdataService(),
process: (query) => this.getCustomerApiCall(query),
} as OdataServiceApi
};
}
}
getCustomerApiCall(query: string) {
let finalQuery = query;
// in your case, find the boolean value from the column and modify query
// your logic to modify the query string
// untested code, but it would probably look similar
if (query.includes('LockoutEndDateUtc%20eq%20true')) {
// calculate new date and replace boolean with new date
finalQuery = query.replace('LockoutEndDateUtc%20eq%20true', 'LockoutEndDateUtc%20le%202022-06-28T12%3A59%3A25Z');
}
return finalQuery;
}
Another possible solution but requires a bit more work.
If I'd be using a regular grid, without backend service and without access to the query string, I would probably add an external drop down outside of the grid and also add the date column and then control filters in the grid by using dynamic filtering. You can see a demo at Example 23, the principle is that you keep the column's real nature (date in your case) and filter it, if you want something like a "below today's date" then add an external way of filtering dynamically (a button or a drop down) and control the filter dynamically as shown below (from Example 23)

PivotTable.JS Callback implementation problem

I have implemented PivotTable.JS in Filemaker and it works great. I've added the callback code and that function seems to be working when I click on a cell. When click on the cell I get the dialog "Message from webpage", I assume I still need to add some code to show the records that makes up the content of the click cell. What would be the approach to show the records, unfortunately I am not java script savvy.
$("#output").pivotUI(
$.pivotUtilities.tipsData, {
cols: ["Quarter Latest"],
rows: ["Customer"],
vals: ["Wt Forecast"],
aggregatorName: "Sum",
rendererName: "Table",
renderers: $.extend(
$.pivotUtilities.renderers,
$.pivotUtilities.c3_renderers,
$.pivotUtilities.export_renderers
),
rendererOptions: {
table: {
clickCallback: function(e, value, filters, pivotData){
var names = [];
pivotData.forEachMatchingRecord(filters,
function(record){ names.push(record.Name); });
alert(names.join("\n"));
}
}
}
});
I guess the problem is that you are pushing into the array 'names' a field 'Name' that is not available in your recordset.
You can access de complete json returned on the clickCallBack by making a small change to your code.
$("#output").pivotUI(
$.pivotUtilities.tipsData, {
cols: ["Quarter Latest"],
rows: ["Customer"],
vals: ["Wt Forecast"],
aggregatorName: "Sum",
rendererName: "Table",
renderers: $.extend(
$.pivotUtilities.renderers,
$.pivotUtilities.c3_renderers,
$.pivotUtilities.export_renderers
),
rendererOptions: {
table: {
clickCallback: function(e, value, filters, pivotData){
var fullData = [];
pivotData.forEachMatchingRecord(filters,
function(record){ fullData.push(record); });
console.log(fullData);
}
}
}
});
Perhaps you can later pass that JSON to another function and build a table.

data change doesn't reflect in vue application

In my Vue application I am trying to create a simple table with changeable column sequence. In the data structure I keep all column data with its thead. I use compute to calculate rows from column data using matrix transposion. However any change I do to dynamicTable.columns doesn't reflect in the view.
function transpose(a)
{
return a[0].map(function (_, c) { return a.map(function (r) { return r[c]; }); });
// or in more modern dialect
// return a[0].map((_, c) => a.map(r => r[c]));
}
var tData = {
columns:[
{thead:'isbn',
tdata:[1,2]},
{thead:'name',
tdata:['rose','flower']},
{thead:'price',
tdata:['10','15']},
{thead:'author',
tdata:['john','jane']},
{thead:'page count',
tdata:['396','149']},
{thead:'print date',
tdata:['2001', '1996']}
]
}
var dynamicTable = new Vue({
el: '#dynamicTable',
data: tData,
computed:{
rows: function(){
arr = [];
this.columns.forEach(function(element){
arr.push(element.tdata);
});
return transpose(arr)
}
}
})
For example I want to change the order of isbn column with price,
a=dynamicTable.columns[0]
b=dynamicTable.columns[2]
dynamicTable.columns[0]=b
dynamicTable.columns[1]=a
data changes but changes are not reflected. What is the problem here?
As mentioned in the documentation, this is a JavaScript limitation. Direct changes to an array are not detected by Vue.
One workaround for this, is to use Vue.set(), as instructed in the link.

How to generate jQuery DataTables rowId client side?

The jQuery DataTables reference shows an example of setting the rowId option to a column from the data source (server side). This setting is used for the "select" extension and retaining row selection on Ajax reload.
Is there any way to generate the row identifier value 1) client side, or 2) as a combination of multiple columns from the data source?
Example data source:
{
"data": [
{
"aid": 5421,
"bid": 4502,
"name": "John Smith"
}
}
Code:
$("#datatable").DataTable({
select: true,
//rowId: "aid" each row ID is the value of the "aid" column
// e.g., <tr id="5421">
//rowId: 0 each row ID is the value of the 0-indexed column
// e.g., <tr id="5421"> (same as above)
rowId: [0, 1] // How? row ID combined value of 2+ columns
// e.g. <tr id="5421-4502">
rowId: "random" // How? random generated client-side ID
// e.g., <tr id="id34e04">
});
Apparently there's no way to do this directly. As a workaround, you could use the ajax.dataSrc option and/or the rowId option:
// Example using dataSrc option to manipulate data:
$("#example").dataTable({
ajax: {
url: "data.json",
dataSrc: function (json) {
for (var i = 0, ien = json.data.length; i < ien; i++) {
json.data[i][0] = 'View Message';
}
}
}
});
This worked for me:
$("#datatable").DataTable({
...
'createdRow': function(nRow, aData, iDataIndex) {
$(nRow).attr('id', 'row' + iDataIndex); // or if you prefer 'row' + aData.aid + aData.bid
},
...
});
I updated it from a question that seems to be a duplicate of this one. The createdRow callback is documented here.

How can I implement new line in a column (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.