Rajat Gupta
Rajat Gupta

Reputation: 26597

What value to convert in getAsObject() & getAsString() methods of JSF Converter class

I'm using PrimeFaces autocomplete with pojos, that shows results of a search. My code as follows:

 <p:autoComplete id="searchBar" completeMethod="#{search.fetchSuggestions}" value="#{search.selectedSuggestion}" 
                 var="searchResult" itemLabel="#{searchResult.entityName}" itemValue="#{searchResult.entityId}" converter="searchResultsConverter" >
      <p:column>  
           <p:graphicImage value="/images/#{searchResult.entityDisplayPic}" width="40" height="50"/>  
      </p:column>  

      <p:column>  
           #{searchResult.entityName}  
      </p:column>  
 </p:autoComplete>  

What values do I need to convert in the getAsObject() and getAsString() methods in the converter class?


My searchResult class looks like this:

public class SearchResult {//object that hold the data of a single search result
    private int entityId;// may be userId/ groupId or etc etc in different cases
    private String entityName;
    private String entityDisplayPic; 
}

Upvotes: 2

Views: 6135

Answers (2)

Jim Tough
Jim Tough

Reputation: 15240

I have converters in my webapp that "convert" between a retrieved database entity (I'm using JPA entities) and a string. An example would be when I'm populating a drop-down list box in a form. In this case, the string returned from the getAsString() method just an integer-based primary key for the JPA entity (converted to a string). The getAsObject() method then just needs to do a simple database lookup using the primary key to get the object.

The point is, your value from getAsString() just needs to contain enough info to allow your server-side code to get back a unique object. How you implement getAsObject() is totally up to you. Sometimes it's trivial and sometimes it's not.

Upvotes: 0

M Platvoet
M Platvoet

Reputation: 1654

The goal of a Converter is converting from a string representation to a concrete object and vice-versa. So in this case you need a String that uniquely identifies/describes your SearchResult object. It's really up to you what this string representation looks like. It might an aggregation of the fields used in the class, it might be an unique identifier that enables you to load the concrete object from some other (database)resource.

Upvotes: 1

Related Questions