How to show the actual item's index in datatacle? - javascript

In my app, I need to show the index of the data entry in the first datatable column and it must work after DnD (so I suppose the column should be dynamically refreshed). But how is it possible in Webix datatable?
For now, I am able to get the index manually using getIndexById, but this method doesn't work in the column template. For instance:
/* inside the config */
drag:true,
columns:[
{ id:"index", template:function(obj){
console.log(obj.id);
// doesn't work:
// console.log(datatable.getIdByIndex(obj.id));
} },
{ id:"id" },
{
id:"title", fillspace:true, sort:"string"
}
],
ready:function(){
this.eachRow(
function (row){
console.log( this.getIndexById(row) ) // works
}
)
}
});
/* somewhere else */
console.log(datatable.getIdByIndex(4));
Code sample.
Is this possible at all? Thanks.

To get the index of row (data entry) you must define your index template as:
template: function(obj){
return $$("dt").getIndexById(obj.id); }
where "dt" is the id of your datatable. It automatically changes the index when you perform any DnD operation. Further, check the snippet here.

Related

Defining Kendo UI Grid Column Templates with a Function that returns a string

I need to create a Kendo UI for jQuery column which uses a function to determine the template. Essentially the data I am receiving from the backend gives me a number, and I need to match up that number to the corresponding entry in another database table. Once the match is found, I need to set the column template to show that entry.
template: function (e) {
countryData.forEach(function (country) {
let countryDesc;
if (country.countryCode == e.countryCode) {
countryDesc = country.description;
return countryDesc;
}
})
}
This is the function that I have written. countryData is an array of JSON objects containing a list of countries with codes, I am matching that code up with e.countryCode to get the correct country. This is then assigned to countryDesc, and returned.
When ran, the columns are just displayed as 'undefined'. I'm confused as to why this isn't working, as if I do this for example: template: "foo", the column would display foo. Surely all i'm doing is returning a string, so this should work?
So after trying loads of things, replacing the .forEach with a plain for fixed this issue.
template: function (e) {
let country;
for (i = 0; i < countryData.length; i++) {
if (countryData[i].countryCode == e.countryCode) {
country = countryData[i].description;
}
return country;
}

jqGrid how to apply custom filtering / search

I have a jqGrid with a filterToolbar. On one of my columns I want to do a search where for the "filter test", my custom function is called and obviously returns a true for yes it passed of false for no.
Can jqGrid do this, if so, how?
Using the free fork of jqGrid you can use the following
in your colModel add the value searchoptions as so:
{name:'FIELD',width:120,searchoptions:{ sopt: ["cust"] },label:"Field name"}
then add the following property to jqGrid
customSortOperations: {
// the properties of customSortOperations defines new operations
// used in postData.filters.rules items as op peroperty
cust:{
operand: "Custom",// will be displayed in searching Toolbar for example
text: "Custom", // will be shown in Searching Dialog or operation menu in searching toolbar
filter: function (options) {
// The method will be called in case of filtering on the custom operation "cust"
// All parameters of the callback are properties of the only options parameter.
// It has the following properties:
// item - the item of data (exacly like in mydata array)
// cmName - the name of the field by which need be filtered
// searchValue - the filtered value typed in the input field of the searching toolbar
// Get cell data as lowercase
var fieldData = options.item[options.cmName].toLowerCase(),
// Get search terms all in lowercase
terms = $.map(options.searchValue.split(" "), function(val){ return $.trim(val).toLocaleLowerCase(); }),
// A match found
match = false;
// Loop through terms and see if there is a match in the row cell data
$.each(terms, function(i,v)
{
if(fieldData.indexOf(v) != -1)
{
match = true;
// Quit the each loop
return false;
}
});
return match;
}
}
},

SAPUI5 Javascript - Get first and last elements of array for each unique property

SAPUI5 - I have an array of objects and one of the properties in those is 'Category'.
For example say I have 2 different types of Category, 'Front Shop' and 'Production Area', what I need to do is to be able to get the first value of each and the last value of each, and then set the enabled property of a button as enabled/disabled.
I'm currently using undercore js (_.each) to loop through to perform some other logic, so can include additional logic here.
Not sure if Underscore has a built in function for this?
Or could someone point me in the right direction on how to do this?
I've got my first pass at what was wanted where I get the very first result and the last result, but now need to set this for each unique category.
Example code below:
// Set view data
oViewData.Questions = oQuestions.results;
oViewData.Questions.TotalNumberOfQuestions = oQuestions.results.length;
// Loop Questions, to get Category Desc and Competency Desc values from relevant Sets
_.each(oViewData.Questions, function (result, index) {
// Read and set Category Desc
this.getView().getModel("Survey").read("/CategorySet", {
filters: [new Filter("CategoryId", FilterOperator.EQ, result.CategoryId)],
success: function (oData) {
oViewData.Questions[index]._CategoryDesc = oData.results[0].CategoryDesc;
this.setViewData(oViewData);
}.bind(this),
error: function (oError) {}.bind(this)
});
// Read and set Competency Desc
this.getView().getModel("Survey").read("/CompetencySet", {
filters: [new Filter("CompetencyId", FilterOperator.EQ, result.CompetencyId)],
success: function (oData) {
oViewData.Questions[index]._CompetencyDesc = oData.results[0].CompetencyDesc;
this.setViewData(oViewData);
}.bind(this),
error: function (oError) {}.bind(this)
});
// Set all move up / down buttons to enabled
oViewData.Questions[index]._MoveUpBtn = true;
oViewData.Questions[index]._MoveDownBtn = true;
// if category id is the first one in the list
}.bind(this));
// Overwrite first move up button and last move down btn to disabled
oViewData.Questions[0]._MoveUpBtn = false;
oViewData.Questions.slice(-1)[0]._MoveDownBtn = false;
// Set view data
this.setViewData(oViewData);
First, you can iterate through arrays with native JavaScript.
_.each(array, function(item) {}) is the same as array.forEach(function(item) {}).
Second, you can use the built-in filter function for your actual question:
const aFrontShopItems = oViewData.Questions.filter(function(oItem) {
return oItem.Category === "Front Shop";
}
If oViewData.Questions is an array then the function passed to filter is applied to every element. If the condition (e.g. oItem.Category === "Front Shop") is true then the element is added to the new array aFrontShopItems. Obviously you need to call filter a second time to get the Production Area items. You can then apply your logic to the first and last items of your new arrays.

How to loop through all rows in DataTables jQuery?

I am using jquery plugin DataTables for building nice table
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
I finally found:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.
tableName.rows().every(function(){
console.log(this.data());
});
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each() method provided by jQuery.
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
for example, this data has three fields UserID, UserName and isActive and we want to show only active users
The following code will return all the rows.
var data = $('#myDataTable').DataTable().rows().data();
We will print only active users
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});

Get Devexpress Gridview Sort By and Sort Order in Javascript

I am implementing Devexpress Grid Control in MVC. I was stuck at a point where i need the current Sorted By column and Sort Order (asc/desc) in javascript. I also tried the clientSide Event OnColumnSortingChanged(s , e) , it is only providing the name of the column at click event not from the gridview javascript object.
Got the answer after research...
Have to add CustomJsProperty to the control in the partial view as below
settings.CustomJSProperties = (s, e) =>
{
var Grid = s as MVCxGridView;
var result = new System.Collections.Hashtable();
foreach (var col in Grid.AllColumns)
{
var dataCol = col as GridViewDataColumn;
if (dataCol != null)
{
if (dataCol.SortIndex == 0)
{
e.Properties["cpColumnsProp"] = new Dictionary<string, object>()
{
{ "sortcolumn", dataCol.FieldName },
{ "sortorder", ((Convert.ToString(dataCol.SortOrder).Equals("Ascending")) ? "asc" : "desc")}
};
}
}
}
};
Handle the ColumnSortingChange event as follows
function gvChartList_OnColumnSortingChanged(s, e) {
$("#hdsortname").val(e.column.fieldName); // contains the sort column name
$("#hdsortorder").val(((s.cpColumnsProp.sortcolumn == e.column.fieldName) ? "desc" : "asc")); // contains the sort column order
}
Last but not the least, One must have to define the default sort index and sort order for the column
settings.Columns.Add(col =>
{
// column details
col.SortIndex = 0;
col.SortAscending();
});
I recently needed similar, where I wanted to save the column order, sort order, and filter information; such that a user could create saved views of a grid, and not have to keep re-entering all these preferences.
I found that in an event CustomJSPropeties I could interact with a sender being an ASPxGridView, such that I could grab a needed value from ASPxGridView.SaveClientLayout(). Also useful here can be the FilterExpression, and the VisibileRowCount - if you want to use the filter expression for exporting, but only when the VisibleRowCount is less than a certain threshold (this is the number of rows shown in the bottom pager area)
settings.CustomJSProperties = (s, e) =>
{
ASPxGridView gridView = (ASPxGridView)s;
e.Properties["cpGridFilterExpression"] = gridView.FilterExpression; //Make Filter Expressions Availabe to JavaScript
e.Properties["cpVisibleRowCount"] = gridView.VisibleRowCount; //Make Visible Row Count Availabe to JavaScript
e.Properties["cpLayout"] = gridView.SaveClientLayout(); //Get Layout String and make it available to JavaScript
};
So what does this do? Properties defined in this event are available as properties of the javascript grid view object. So here we grab these values when we can, and place them in a place where we normally cannot access them.
And then, right from JavaScript we can now access GridView.cpLayout (where GridView is the name/id supplied to your grid.)
<script type="text/javascript">
$(document).ready(function () {
$('#saveButton').click(
function () {
var layout = GridView.cpLayout;
//Perform Save...
}
);
});
</script>
To be clear, this "layout" contains sort order, visible column info, and filter information.
Layout:
https://documentation.devexpress.com/#AspNet/CustomDocument4342
https://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridViewASPxGridView_SaveClientLayouttopic
CustomJSProperties:
https://documentation.devexpress.com/#AspNet/DevExpressWebMvcGridViewSettings_CustomJSPropertiestopic
Note: I add this solution here because this is what I found when I was searching for my issue. As one can see, these are similar topics of accessing the AspxGridView (base of) or MVCGridView within a CustomJSProperties event handler.

Categories

Resources