How to reuse two or more variables in a custom column in DataTables? - datatables

I found this answer in this question.
In the answer, it says:
"mData": "Name",
"mRender": function (data, type, row) {
return "<a href='Admin/Categories/Edit/" + data + "'>EDIT</a>";
I'm look for a way to include two variables, for instance:
"mData": ["Name", "User"],
"mRender": function (data, type, row) {
return "<a href='Admin/Categories/Edit/" + data[0] + data[1] + "'>EDIT</a>";
Is there any way I can do that?

The row argument contains all the data for that row. The data argument contains the data specified in the column options. So you would do something like
data: 'Name',
render: (data, type, row) => `EDIT`
or you could set the data property as null and just use the row argument
data: null,
render: (data, type, row) => `EDIT`

Related

Bootstrap-Vue: Sorting table column based on Formatter data

So right now I have data presenting the way that is required. This is how I have the field set up
{
key: "pendingTime",
formatter: (value, key, item) => {
return this.pendingSinceDate(_, key, item);
},
label: "Pending Since",
sortable: true,
},
And this is the function being used.
pendingSinceDate(value, key, item) {
const timeMath = (day1, day2) => {
const hours = dayjs(day1).diff(day2, "hours");
return Math.trunc(hours / 24);
};
const timeFormat = dayjs(
item.operations.localAreaOrder.dateLastModified,
).format("L");
const dayCount = timeMath(
dayjs().startOf("day"),
dayjs(item.operations.localAreaOrder.dateLastModified).startOf("day"),
);
key = `${timeFormat} - ${dayCount} ${dayCount === 1 ? "Day" : "Days"}`;
return key;
},
I've been reading about sortByFormatted and sort-compare and trying to understand implementation. Is there a way to have sorting work based on timeFormat as we need sorting based on that date.
From I'm understanding with sortByFormatted can accept a function or true. So I tried to see and created a function to console.log just to make sure things work.
Not getting anything back with this function when I add it to sortByFormatted
sortedByFormatTest(value, key, item){
console.log(value, key, item)
},
Anyone got direction on where to look or tips to get started on figuring out how to sort on that?

Prepopulate the text box for dataTables individual column searching

this should be easy but all the examples I can find are specific to the "general search" text box.
I'm trying to prepopulate an individual column search box, for example the "Name" field.
I don't need the code to do the search, just code to put a value in that "Search Name" text field.
There are 2 steps you can take to achieve this.
Step 1:
Use the searchCols option to set up your initial search terms. For example:
"searchCols": [
{ "search": "sat" }
]
This will cause column 1 to be filtered on the string sat.
If you want to use additional or different column filters, you can use null to skip columns - for example:
"searchCols": [
null,
{ "search": "foo" }
null,
{ "search": "bar" }
]
The above example will filter the 2nd and 4th columns.
Step 2:
You can take the existing code which creates the input fields in the table's footer cells, and modify that code to (a) use an index, and then (b) use the index to target the specific column(s) you want to pre-populate:
$('#example tfoot th').each(function ( idx ) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
if ( idx === 0 ) {
$(this).find( 'input' ).val( 'sat' );
}
});
In the above fragment, I took the code linked to in the question and added the idx variable, and then used that to target the first input field, and populate it with "sat".
Without step 2, the DataTable will not show you the values being used to perform filtering.
initComplete: function () {
this.api().columns().every( function () {
var column = this;
if ($(column.header()).hasClass('datatable_search')) {
var that = this;
//player var taken from url
if (column.header().innerText.includes('Players') && players.length){
//prepopulate the input field
$( 'input', this.header() ).val(players)
//use the url.players arg in the search and redraw
this.search( players ).draw();
}
$( 'input', this.header() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'id' of undefined" while trying to get array of ids from selected rows in b-table

I am using bootstrap-vue tables selectable prop i can get the selected rows but that contain all the properties of the rows but i want only the id of the selected rows.
to do this tried this
getids(){
for (var i = 0; i <= this.selected.length; i++) {
this.filteredORD_NO.push(this.selected[i].id)
} }
where selected [] is the selected array which contain all properties of the row and filteredORD_NO[] is an array which contain ids extracted from the selected [] array. this does work when i call the function directly eg by btn , but shows "Error in v-on handler: "TypeError: Cannot read property 'id' of undefined" when i try to sed this data to the backend.
"
assignmethod() {
this.getids(),
this.WorkToteam[0] = this.filteredORD_NO,
this.WorkToteam[1] = this.selectedteam,
console.log(WorkToteam);
this.axios({
method: "POST",
url: "/path/to/backend",
data: this.workToteam,
headers: { Authorization: "Bearer " + localStorage.getItem("ikey") },
})
.then(
(response) => (
console.log("response"),
)
)
.catch((error) => console.log(error))
.finally(() => (this.loading = false));
},
filteredORD_NO must be an array
declaring like filteredORD_NO: [], solved the issue.

Datatables mDataProp: val param undefined

I'm working on implementing a custom filter value where existing html tags are stripped away for each applicable table column values.
(The reason is that filtering the data also accounts for values inside the html tags, and this is not desired.)
This is a legacy code base, using datatables v1.9.0.
The table is constructed using params, such as aoColumns, aaData.
For table data is using array of arrays: i.e:
aaData = [
['12450','<a href='javascript:doStuff(123, 456)>value2</a>', 'User 1', '$500'],
['12455','...','...','...'],
['12462','...','...','...'],
['12314','...','...','...'],
[...],
...
]
Table has to use mDataProp for applicable aTargets
The function signature is:
tableOptions["aoColumnDefs"] = [
{
"mDataProp": function (source, type, val) {
console.log("source ", val); // This returns: row array
console.log("type ", type); // This returns each type (except for 'set')
console.log("val ", val); // This returns: undefined
var obj = {};
var temp = angular.element('div');
temp.innerHTML = val;
if (type === 'set') {
obj.value = val;
obj.value_filter = temp.textContent || temp.innerText;
console.log(obj.value_filter);
return;
} else if (type === 'filter') {
return val;
} else if (type === 'sort') {
return val;
}
return obj.value;
},
"sDefaultContent": '',
"aTargets": [ 1 ]
},
]
The issue is that val parameter inside mDataProp always returns undefined, so the table data population would error out, if not for the sDefaultContent property.
See this fiddle.
Why cannot the mDataProp get the val parameter populated? Does mDataProp support an array of arrays as data source? (The documentation is not clear about this)
After digging through a bit I found out that when mDataProp is used as a function, it does not have any reference to the data being passed to the datatable from the javascript array variable, thus returning undefined for val.
The workaround for this particular case is to use direct array position references in the source parameter, depending on the aTargets value to be used. (If using "aTargets": [ 1 ], then have to call source[1] in the mDataProp function).
I did not use if (type === "set"){}, 'cause I could not access it.
"mDataProp": function(source, type, val) {
var obj = {};
obj.value = source[1]; // Set column value
// Process value as desired ...
obj.value_filter = obj.value + ' foobar';
// Return value for filtering
if (type === 'filter') {
return obj.value_filter;
}
// Return original value for display, sort, etc.
return obj.value;
}
Click updated fiddle.

Function parameter as this.variable

I'm using Vue.js and would like to use one method for multiple things:
data: {
genders: [],
months: [],
}
methods: {
getModels:function(cat,model) {
$.getJSON('/api/models/' + cat + '/' + model, function(data) {
this.model = data;
}.bind(this));
},
},
created: {
this.getModels('core', 'genders');
this.getModels('core', 'months');
},
In the method I want to be able to select the correct array with the data that has been fetched. But the code is instead looking for the 'model' data when I need it to look for the 'genders' and 'months' data.
If you want to access to some data by its name, you should do
model = 'genders' // just to ilustrate the example
this[model] = data
because this.model is equal to this['model'], and in the above code, this[model] is equal to this['genders'] or this.genders