Graphene
Graphene copied to clipboard
Custom Sort and Filter Functions in DataGrid Initializers
Problem
There are some kinds of data that I'd like to store in a DataGrid that doesn't sort properly using a normal alphanumeric sort, e.g. dates. Currently, for dates, I have to return a UNIX timestamp or ISO 8601 date from the API, then set e.model.display to the desired format on the model:draw event. I'm sure this problem exists for other kinds of data besides dates, so I propose the following general solution.
Proposed Solution
Add two optional parameters to the app.grid initializer: sortFuncs and filterFuncs.
sortFuncs contains key-value pairs where the key is the name of the column, and the value is a function that compares two values and returns the lesser of the two. This function would then be used to sort the column, e.g. Array.prototype.sort(sortFuncs[columnName]).
filterFuncs contains key-value pairs where the key is the name of the column, and the value is a function that takes a value from the column and the string in the filter field, and returns true if the value should be included given the filter string and false otherwise.
app.grid("myGrid", {
el: "#my-grid",
form: "myGridForm",
resource: "get_fields",
sortFuncs: {
"Date": (a,b) => moment(a, "MM/DD/YY") < moment(b, "MM/DD/YY"),
"Mystery Data": (a, b) => mysteryDataIsLesser(a, b)
},
filterFuncs: {
"Mystery Data": (val, filterString) => includeMysteryInResults(val, filterString)
}
);