Search code examples
jsfprimefacesfilterdatatableenums

Primefaces dataTable, filter on localized enum values


I have a p:datatable that is populated by a list of domain objects

Each domain object has a value that is tied to an enum PrivateIndustry : P, K or N , that corresponds to a database value.

these values are then presented in the p:dataTable via localization, labels_LOCALE.properties to make them human readable, with the com.package.PrivateIndustry.P/K/N syntax.

This works okay for readability, but when i Use PF('dataTableId').filter() to filter the dataTable, I cannot filter for the localized values, only the pure enum values (ie P, K or N)

ie:

    <p:column headerText="#{labels.header}"
         filterBy="#{domainobject.privateIndustry}" filterStyle="display: none"
         sortBy="#{domainobject.privateIndustry}" >
         <h:outputText value="#{domainobject.privateIndustry}"/>
    </p:column>

I can remedy this by populating the names in the domain object as String using ResourceBundle.getString("com.package.PrivateIndustry...") but this seems rather unneccesary and convoluted.

Can I parse filterBy="" with a better value, or make PF().filter() work on the client side data?


Solution

  • This is the way I solved the functionality in code rather than in xhtml:

    upon creation of the domain objects, in the constructor,call a method that generates a String containing the parsed String from the enum value:

    import java.util.ResourceBundle;
    import javax.faces.context.FacesContext;
    
    public class DomainObject   {
        private PrivateIndustry privateIndustry;
        private String enumStringValue;
    
        public void generateEnumStringValue() { 
            ResourceBundle rb= ResourceBundle.getBundle("labels",FacesContext.getCurrentInstance().getViewRoot().getLocale());
            this.enumStringValue = rb.getString("com.package.DomainObject.PrivateIndustry." + privateIndustry.name());
        }
        public String getEnumStringValue() {
            return emumStringValue;
        }
    
        public enum PrivateIndustry {
    
            P("Private"),
    
            N("Industry"),
    
            K("Combined");
            private final String name;
    
            PrivateIndustry(String name) {
                this.name = name;
            }
    
            public String getName() {
                return name;
            }      
        }
    }
    

    and then, in the bean:

    public String getEnumStringValue(DomainObject domainObject) {
    
        return domainObject.getEnumStringValue();
    }
    

    and finally:

    <p:column headerText="#{labels.header}"
              filterBy="#{backingBean.getEnumStringValue(domainObject)}"
              sortBy="#{backingBean.getEnumStringValue(domainObject)}">
        <h:outputText value="#{domainObject.privateIndustry}"/>
    
    </p:column>