Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primefaces DataTable not sorting properly

I'm Java EE webapp developer (spring, hibernate, jsf, primefaces) and I found the issue with primefaces component DataTable. The issue concerns column sorting, particularly sorting of words with special characters.

In my language (Czech) we use characters like (č, ř, ž etc.) and words starting with these characters are sorted at the end of the table. And this is the problem. They should be sorted after appropriate letter, e.g. "č" should be after "c", "ř" should be after "r" etc. and not after all records without special characters.

I'm already using the CharacterEncoding filter provided by Spring Framework which should force the charset (UTF-8) to every request and response. But it doesn't solve the issue. Here is the configuration of the filter:

<filter>
    <filter-name>charEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

Is there a way to correct this behaviour?

like image 218
Littlebox Avatar asked Apr 17 '15 21:04

Littlebox


1 Answers

I hope doing it programatically like this will work for you too. entities is here just a List<String>:

<p:dataTable value="#{testBean.entities}" var="ent">
    <p:column headerText="..." sortBy="#{ent}" sortFunction="#{testBean.sort}">
        #{ent}
    </p:column>
</p:dataTable>

Bean method:

public int sort(Object ent1, Object ent2) {
    String s1 = (String) ent1;
    String s2 = (String) ent2;

    Collator collator = Collator.getInstance(new Locale("cs"));  //Your locale here
    collator.setStrength(Collator.IDENTICAL);
    return collator.compare(s1, s2);
}

The Collator can of course be made a property on the bean for maybe a bit performance.

If it's only the default sorting you're after just move the above sortBy and sortFunction to the p:datatable-tag.

like image 173
Jaqen H'ghar Avatar answered Oct 23 '22 03:10

Jaqen H'ghar