I have a datatable with 10 columns which are grouped in 4:4:2 manner. Now the first two groups(of 4) are fixed while the last 2 can be added to any of the groups(single or both at a time) based on a condition. Is there a way to set indexes for columns so that they can be ordered based on a condition ? I see that Primefaces reorder using drag n drop gives the kind of result Im looking for except I want the reordering to be programmable and set before the table is displayed.
1 Answers
I had basically the same problem: after allowing the user to rearrange columns, it is easy to save the arrangement into a cookie, but how to restore the order a day later?
As far as I know, there are no primefaces method to this but can be hacked with a little javascript. (I tried with primefaces 6.0)
1) Give all the columns unique styleClasses, like:
styleClass="mystyle col0"
styleClass="mystyle col1"
styleClass="mystyle col2"
...
2) Convert the styleClass strings into valid css selectors, and store the required order of columns as an order of those, like:
".mystyle.col2,.mystyle.col0,.mystyle.col1"
Put it into a cookie, or store and get back as you like.
3) Write a javascript function to rearrange the cells into the required order:
function reorder() {
var o = getCookie('orderString');
var a = o.split(",");
for (var i = a.length - 1; i >= 0; i--) {
$(a[i]).each(function() {
$(this).prependTo($(this).parent())
});
}
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length === 2)
return parts.pop().split(";").shift();
}
(Don't use EL expressions to get back the order string from a backing bean, because it evaluates on page render, so won't update if the user rearranges the columns again.)
4) Execute reorder() "every time you need it".
You'll certainly need it on page loads:
$(document).ready(function() {
reorder();
});
but also on paging events, so add something like this:
<p:ajax event="page" oncomplete="reorder();" />
(And perhaps other times I've not met yet.)