I have been trying to set a presort similarly to this: https://www.primefaces.org/primereact/showcase/#/datatable/sort
The problem I am facing is that I would like to sort on render by a column which has a sortFunction defined by me.
I have a working sortFunction, but if I give the DataTable a sortField, it does not use it.
On render the nulls are in front, which is the default sort of sortable but
clicking the header uses the proper sortFunction, which sorts alpahabetically and sends nulls to the end
Is it possible to solve this somehow or should I let the presorting go?
Edit: I presorted the data and gave it to the DataTable that way, so it works but it is far from elegant, also it does not show the column to have the sorted arrows on render, but it might be helpful for someone:
const dataTableSortFunction = (value: any[]) => (event: ColumnSortParams): any[] => {
return [...value].sort((data1, data2) => {
const value1 = data1[event.field];
const value2 = data2[event.field];
if (value1 == null && value2 == null) return 0;
if (value2 == null) return -1;
if (value1 == null) return 1;
if (typeof value1 === "string" && typeof value2 === "string")
return value1.localeCompare(value2) * event.order;
if (value1 < value2) return -1 * event.order;
if (value1 > value2) return 1 * event.order;
return 0;
});
};
const myProductSort = dataTableSortFunction(products);
const preSortedProducts = myProductSort({ field: "category", order: -1 });
...
<DataTable value={preSortedProducts} className="p-datatable-sm">
<Column field="code" header="Code" sortable></Column>
<Column field="name" header="Name" sortable></Column>
<Column
field="category"
header="Category"
sortable
sortFunction={myProductSort}
></Column>
<Column field="quantity" header="Quantity" sortable></Column>
<Column field="price" header="Price" sortable></Column>
</DataTable>
Related
In the slickgrid I'm able to set the sort column and it's sort direction using the grid.SetSortColumn(colName,true/false). This only sets the sorting glyph but does no sorting. Is there a way to call the sort event handler. I've defined the sort handler like grid.onSort.subscribe(function(){});
The behavior you are observing is correct.
grid.setSortColumn(columnId, isAsc);
only updates the glyph on the sort column.
In your case, you will initially need to sort the data, and then use setSortColumn to update the glyph on sortColumn. You can reuse sorter used in onSort event like this:
var gridSorter = function(columnField, isAsc, grid, gridData) {
var sign = isAsc ? 1 : -1;
var field = columnField
gridData.sort(function (dataRow1, dataRow2) {
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2) ? 0 :
((value1 > value2 ? 1 : -1)) * sign;
return result;
});
grid.invalidate();
grid.render();
}
var grid = new Slick.Grid($gridContainer, gridData, gridColumns, gridOptions);
//These 2 lines will sort you data & update glyph while loading grid
//columnField is field of column you want to sort initially, isAsc - true/false
gridSorter(columnField, isAsc, grid, gridData);
//I had the columnField, columnId same else used columnId below
grid.setSortColumn(columnField, isAsc);
grid.onSort.subscribe(function(e, args) {
gridSorter(args.sortCol.field, args.sortAsc, grid, gridData);
});
How I arrived on this solution?
Read comments here. https://github.com/mleibman/SlickGrid/issues/325
dataView.fastSort does the job. You can then use setSortColumn to set the sorting glyph.
I have multiple column sort enabled, I had to change the function to pass the correct sort column.
grid.onSort.subscribe(function(e, args) {
gridSorter(**args.sortCols[0].sortCol.field**, **args.sortCols[0].sortAsc**, grid, gridData);
});
You can trigger click event on the column header...which does sorting
I fixed the issue like this...
$('.slick-header-columns').children().eq(0).trigger('click'); // for first column
I was inspired by Mr.Hunts answer but I took a slightly different approach to extend the current grid.setSortColumn(columnId, isAsc) to grid.setInitialSortColumn(columnId, isAsc). This will apply the sort and do everything grid.setSortColumn does.
var thisGrid = { //Your grid obj
columns: , // Your columns object
grid: , // new Slick.Grid....
}
thisGrid.grid.onSort.subscribe(function (e, args) { // ar var cols = args.sortCols;]
thisGrid.grid.customSort(args);
});
thisGrid.grid.customSort = function (args) {
var cols = args.sortCols;
thisGrid.dataView.sort(function (dataRow1, dataRow2) {
if (cols) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field],
value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
}
return 0;
});
}
thisGrid.grid.setInitialSortColumn = function (columnId, ascending) {
thisGrid.grid.setInitialSortColumns([{
columnId: columnId,
sortAsc: ascending
}
]);
};
thisGrid.grid.setInitialSortColumns = function (cols) {
sortColumns = cols;
$.each(sortColumns, function (i, col) {
var columnIndex = thisGrid.grid.getColumnIndex(col.columnId);
var column = thisGrid.columns[columnIndex];
if (col.sortAsc == null) {
col.sortAsc = true;
}
var args = {
grid: thisGrid.grid,
multiColumnSort: true,
sortCols: [{
sortCol: column,
sortAsc: col.sortAsc
}
]
}
thisGrid.grid.setSortColumn(col.columnId, col.sortAsc);
thisGrid.grid.customSort(args);
});
};
// Trigger
thisGrid.grid.setInitialSortColumn("dateDue", true);
I can't leave comments due to reputation, which is where this would be most appropriate, however, my answer is in regard to #Premshankar Tiwari and #Siddharth answers.
I preferred the dataView.fastSort option in Siddharth's answer, which works for me in all browsers except IE7 and 8. I didn't test it in IE9 or above. Unfortunately, most on my network run IE7 or 8 due to compatibility issues for legacy applications. BUT, Premshankar's answer works in IE7 and 8.
So, I ended up doing something like this:
if (msie > 0) {
$(".slick-header-columns").children().eq(5).trigger("click");
$(".slick-header-columns").children().eq(4).trigger("click");
} else {
dataView.fastSort('process','unit');
}
where column index (5) = 'unit' and column index (4) = 'process'. Notice that is the reverse order in dataView.fastSort method. I am also using a function that detects IE browser version and assigns it to msie.
My only complaint about utilizing the .trigger method is that if you set up your grid to dynamically hide/show columns, the indexed feature would potentially sort on unintended columns unless you are only calling it on initialization when hide/show capabilities are present.
Maybe it will help you. Looks like SlickGrid is triggering sort to self - so You can trigger it manually if You want.
I'm using multicolumn sorting, and loading saved sort data when initialising the grid.
As expected, setSortColumns set the sorting, but didnt actually apply it, and dataView.reSort() or .fastSort() didnt seem to help, regardless of what point in loading I called them
(I must have missed something, but just couldnt get it to work).
In the end, this worked for me. I call it immediately after populating my dataView from an ajax call.
Its probably not the slickest, so happy to take feedback on board!
function forceResort() {
var sortColumns = grid.getSortColumns();
var cols = [];
$.each(sortColumns, function(index, value) {
var columnId = value.columnId;
var sortAsc = value.sortAsc;
var sortCol = { field: columnId };
var col = { sortCol: sortCol, sortAsc : sortAsc};
cols.push(col);
});
dataView.sort(function (dataRow1, dataRow2) {
var sortResult = 0;
for (var i = 0, l = cols.length; i < l; i++) {
if (sortResult !== 0) {
break;
}
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field] || ''; //handle nulls - otherwise erratic sorting
var value2 = dataRow2[field] || ''; //handle nulls - otherwise erratic sorting
if ($.inArray(field, dateTypeColumns) > -1) {
sortResult = compareDates(value1, value2) * sign;
} else {
if ($.inArray(field, numericColumns) > -1) {
sortResult = compareSimple(value1, value2) * sign;
} else {
sortResult = compareAlphaNumeric(value1, value2) * sign;
}
}
}
return sortResult;
});
grid.invalidate();
grid.render();
}
A more clean solution is not to rely on the arguments to onSort but call getSortColumns instead:
function gridSorter() {
var scol=grid.getSortColumns();
if (scol.length===0) return;
var scolId=scol[0].columnId, asc=scol[0].sortAsc;
data.sort(function(a, b) {
var result = a[scolId] > b[scolId] ? 1 : a[scolId] < b[scolId] ? -1 : 0;
return asc ? result : -result;
});
grid.invalidate();
}
Then do:
grid.onSort.subscribe(gridSorter);
This will allow to reestablish sorting anytime you want (from example after reloading the data with ajax) simply by calling gridSorter()
If you want multiple column sorting:
function grid_sorter(args, grid, dataView) {
let cols = args.sortCols;
console.log(cols)
dataView.sort(function (dataRow1, dataRow2) {
for (let i = 0, l = cols.length; i < l; i++) {
let field = cols[i].sortCol.field;
let sign = cols[i].sortAsc ? 1 : -1;
let value1 = dataRow1[field], value2 = dataRow2[field];
let result = (value1 === value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result !== 0) {
return result;
}
}
return 0;
});
grid.invalidate();
grid.render();
}
grid_sorter(default_sorting, grid_2, dataView_2);
cols is an object like this:
- sortCols {
- length: 2
- 0 : {
"sortAsc: true,
"sortCol": {
"field: column_id
}
}
- 1: {..}
}
I am not sure how to convert this simple foreach to linq.
It seems pretty easy, but I keep getting compile errors?
var createAccount = from TransactionDetail td in transactionDetails
Where
td.ResponseType == ResponseType.SUCCESS AND
td.RequestType == RequestType.CREATE_ACCOUNT
SELECT true;
/* trying to convert this */
bool createAccount = true;
foreach(TransactionDetail td in transactionDetails )
{
if (td.RequestType == RequestType.CREATE_ACCOUNT)
{
if (td.ResponseType == ResponseType.SUCCESS)
{
createAccount = false;
}
}
}
If all you want is a boolean result, you don't need where or select. Use the Any method:
bool createAccount = !transactionDetails.Any(
td => td.RequestType == ... && td.ResponseType == ...);
Suppose we've a grid with sortable columns.
If a user clicks on a column, it gets sorted by 'asc', then if a user clicks the column header again, it gets sorted by 'desc', now I want similar functionality when a user clicks the column third time, the sorting is removed, i.e. returned to previous style, the css is changed back to normal/non-italic etc?
Today I was trying to achieve same thing. I've skimmed through SlickGrid code but didn't find any 'Reset' function. So, I've tweaked the slick.grid.js v2.2 a little bit.
Basically you just need to add a new array - 'latestSortColumns' which will store sort columns state (deep copy of internal SlickGrid sortColumns array).
var latestSortColumns = [];
Optionally add new setting to opt-in for sort reset.
var defaults = {
(...),
autoResetColumnSort: false
};
Change setupColumnSort to reset sort after third click on column's header.
function setupColumnSort() {
$headers.click(function (e) {
// temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328)
e.metaKey = e.metaKey || e.ctrlKey;
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length) {
return;
}
var column = $col.data("column");
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
var sortOpts = null;
var i = 0;
for (; i < sortColumns.length; i++) {
if (sortColumns[i].columnId == column.id) {
sortOpts = sortColumns[i];
sortOpts.sortAsc = !sortOpts.sortAsc;
break;
}
}
**if ((e.metaKey || (options.autoResetColumnSort && latestSortColumns[i] != null && latestSortColumns[i].sortAsc === !column.defaultSortAsc)) && options.multiColumnSort) {**
if (sortOpts) {
sortColumns.splice(i, 1);
**latestSortColumns.splice(i, 1);**
}
}
else {
if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) {
sortColumns = [];
}
if (!sortOpts) {
sortOpts = { columnId: column.id, sortAsc: column.defaultSortAsc };
sortColumns.push(sortOpts);
} else if (sortColumns.length == 0) {
sortColumns.push(sortOpts);
}
}
setSortColumns(sortColumns);
if (!options.multiColumnSort) {
trigger(self.onSort, {
multiColumnSort: false,
sortCol: column,
sortAsc: sortOpts.sortAsc}, e);
} else {
trigger(self.onSort, {
multiColumnSort: true,
sortCols: $.map(sortColumns, function(col) {
return {sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc };
})}, e);
}
}
});
}
Store new state after every sort change in latestSortColumns:
function setSortColumns(cols) {
sortColumns = cols;
var headerColumnEls = $headers.children();
headerColumnEls
.removeClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
$.each(sortColumns, function(i, col) {
if (col.sortAsc == null) {
col.sortAsc = true;
}
var columnIndex = getColumnIndex(col.columnId);
if (columnIndex != null) {
headerColumnEls.eq(columnIndex)
.addClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
});
**for (var i = 0; i < sortColumns.length; i++)
latestSortColumns[i] = { columnId: sortColumns[i].columnId, sortAsc: sortColumns[i].sortAsc };**
}
That's all, should work now.
This is a function I call to reset all columns back to their original order.
It requires one of columns to be set up as not sortable.
In the example below I use the first column of the table, columns[0], which has the field id "locus".
function removeSorting() {
columns[0].sortable = true;
$('.slick-header-columns').children().eq(0).trigger('click');
columns[0].sortable = false;
// clear other sort columns
grid.setSortColumns( new Array() );
}
Then in the typical dataView.sort() function you make an exception for this column:
grid.onSort.subscribe(function(e,args) {
var cols = args.sortCols;
dataView.sort(function (dataRow1, dataRow2) {
for( var i = 0; i < cols.length; i++ ) {
var field = cols[i].sortCol.field;
// reset sorting to original indexing
if( field === 'locus' ) {
return (dataRow1.id > dataRow2.id) ? 1 : -1;
}
var value1 = dataRow1[field];
var value2 = dataRow2[field];
if( value1 == value2 ) continue;
var sign = cols[i].sortAsc ? 1 : -1;
return (value1 > value2) ? sign : -sign;
}
return 0;
});
});
Will the table always be sorted in some order on some column?
If not then you'll have to store a lot of state the first time a column is clicked just in case you want to restore it after a third click.
I have a problem that has been bugging me for quite some time and I'm in desperate need of help due to I am a beginner in .NET.
I am using a GridView to display the query results. However, instead of injecting it directly to the entity/LINQ data source, I manually code the events such as Load, Sorting and Paging. The problem is in the Sorting, I can't keep the ascending/descending state. One of the possible solutions that I can think of is by Caching the state, however, I feel like there is another way that is more neat. Thus, can you guys suggest me any other ideas that suit better?
Thanks a lot in advance!
Below is the code that I use for the sorting. Apparently, e.SortDirection will always equals to ascending no matter how many times I have clicked the Column's Header.
switch (e.SortExpression)
{
case "Album":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.DocumentAlbum.Name ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.DocumentAlbum.Name descending
select doc;
break;
case "Category":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.DocumentCategory.Name ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.DocumentCategory.Name descending
select doc;
break;
case "Title":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.Title ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.Title descending
select doc;
break;
case "Description":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.Description ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.Description descending
select doc;
break;
case "DateCreated":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.DateCreated ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.DateCreated descending
select doc;
break;
case "DateUpdated":
if (e.SortDirection == SortDirection.Ascending)
_orderedResult = from doc in _result
orderby doc.DateUpdated ascending
select doc;
else
_orderedResult = from doc in _result
orderby doc.DateUpdated descending
select doc;
break;
}
Actually, I just found the answer. I used the ViewState function to keep track of the state.
This is the function that I used:
private SortDirection GetSortDirection(string column)
{
// By default, set the sort direction to ascending
SortDirection _sortDirection = SortDirection.Ascending;
// Retrieve the last column that was sorted
string _sortExpression = ViewState["SortExpression"] as string;
if (_sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (_sortExpression == column)
{
string _lastDirection = ViewState["SortDirection"] as string;
if ((_lastDirection != null) && (_lastDirection == "ASC"))
{
_sortDirection = SortDirection.Descending;
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = _sortDirection.ToString();
ViewState["SortExpression"] = column;
return _sortDirection;
}
protected void gvOfflineSub_Sorting(object sender, GridViewSortEventArgs e)
{
IList<SellerDetails> Ilist = gvOfflineSub.DataSource as IList<SellerDetails>;
DataTable dt = ToDataTable<SellerDetails>(Ilist);
if (dt != null)
{
DataView dataView = new DataView(dt);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gvOfflineSub.DataSource = dataView;
gvOfflineSub.DataBind();
}
}
/// <summary>
/// Description:Following Method is for Sorting Gridview.
/// </summary>
/// <param name="sortDirection"></param>
/// <returns></returns>
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
If You are using LINQ then it is very simple to sort
just bind grid like this
var data = (from d in edc.TableName
select new
{
d.Address,
d.InsertedDate,
d.ID
}).OrderByDescending(d => d.ID);
if (data != null)
{
grdList.DataSource = data;
grdList.DataBind();
}
In my search for a expression parser, I found the Dynamic LINQ API. I want to use this API for letting the end user specify some criteria for validation of the business objects.
So my first attempt to use the library succeeds with the following Unit test
var x = Expression.Parameter(typeof(int), "x");
var list = Expression.Parameter(typeof(List<int>), "list");
var e = DynamicExpression.ParseLambda(new[] { x, list }, null, "list.Any(it == x)");
var compiledExpression = e.Compile();
var myList = new List<int> { 24, 46, 67, 78 };
Assert.AreEqual(false, compiledExpression.DynamicInvoke(2, myList));
Assert.AreEqual(true, compiledExpression.DynamicInvoke(24, myList));
However I want to have a slightly more complex syntax as I want to change this
list.Any(it == x) // OK
into
list.Any(i => i == x) // Raises error: No property or field 'i' exists in type 'int'
The second syntax would however allow me to nest lambda's (which is my ultimate goal) like so:
list1.All(i => list2.Any(j => j == i))
Anyone know how to adjust Dynamic.cs to support this syntax?
After some hours of debugging I found the solution myself.
The following unit test succeeds now:
var list1 = Expression.Parameter(typeof(List<int>), "list1");
var list2 = Expression.Parameter(typeof(List<int>), "list2");
var e = DynamicExpression.ParseLambda(new[] { list1, list2 }, null, "list2.All(i => list1.Any(j => j == i))");
var compiledExpression = e.Compile();
var myList1 = new List<int> { 24, 46, 67, 78 };
var myList2 = new List<int> { 46 };
var myList3 = new List<int> { 8 };
Assert.AreEqual(true, compiledExpression.DynamicInvoke(myList1, myList2));
Assert.AreEqual(false, compiledExpression.DynamicInvoke(myList1, myList3));
The changes I have applied to the example Dynamic.cs file:
1) Extend the enum TokenId with the member 'Lambda'
2) Add an IDictionary named internals to class ExpressionParser. Initialize it in the ExpressionParser constructor
3) Replace (starting on line 971)
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value)) {
with
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value) ||
internals.TryGetValue(token.text, out value)) {
4) Replace (starting on line 1151)
if (member == null)
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
with
if (member == null)
{
if(token.id == TokenId.Lambda && it.Type == type)
{
// This might be an internal variable for use within a lambda expression, so store it as such
internals.Add(id, it);
NextToken();
var right = ParseExpression();
return right;
}
else
{
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
}
}
5) Replace (starting on line 1838)
case '=':
NextChar();
if (ch == '=') {
NextChar();
t = TokenId.DoubleEqual;
}
else {
t = TokenId.Equal;
}
break;
with
case '=':
NextChar();
if (ch == '=') {
NextChar();
t = TokenId.DoubleEqual;
}
else if(ch == '>')
{
NextChar();
t = TokenId.Lambda;
}
else {
t = TokenId.Equal;
}
break;