pL4Gu33
pL4Gu33

Reputation: 2085

JSF converter global solution

Normaly i implements my jsf converter as my example. But if i have 10 components that need converter, i need 10 converters, too.

Question: Give it a better solution or a global solution for a jsf converter, so that not every component needs his own converter?

Converter:

@FacesConverter(value="PersonConverter")
public class PersonConverter implements Converter{

@Override
public Object getAsObject(FacesContext context, UIComponent component,
        String value) {
    if(value != null){
        MyBean bean = (MyBean)FacesContext.getCurrentInstance().getViewRoot().getViewMap().get("myBean");
        for(Person p : bean.getSearchedPersons()){
            if(p.getName().equals(value)){  

                return p;
            }
        }
    }
    return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component,
        Object value) {
    if(value != null && value instanceof Person){
        return ((Person)value).getName();
    }
    return null;
}
}

Bean:

@ViewScoped
@ManagedBean
public class MyBean {

@EJB
private PersonService service;

private List<Person> searchedPersons;

private Person selectedPerson;

public void printSelectedPerson(ActionEvent event) {

        System.out.println("Selected Person: "
                + selectedPerson.getName());

}

public List<Person> searchValues(String str) {
    searchedPersons = service.searchPerson(str);
    return searchedPersons;
}

/** GETTER & SETTER */

XHTML:

<h:form id="mainform">
        <p:autoComplete completeMethod="#{myBean.searchValues}" value="#{myBean.selectedPerson}"
        converter="PersonConverter" var="p" itemLabel="#{p.name}" itemValue="#{p}" forceSelection="true"/>          
        <p:commandButton value="Test" actionListener="#{myBean.printSelectedPerson}"/>          
    <p:messages globalOnly="false" autoUpdate="true"/>
</h:form>

Upvotes: 1

Views: 683

Answers (2)

Makky
Makky

Reputation: 17461

If you want a generic converter then Omnifaces SelectItemsConverter is the best in all.

Omniface SelectItemConverter

If you don't want to use Omnifaces then look at answer here

Upvotes: 1

user1983983
user1983983

Reputation: 4841

If you want to use that converter everywhere for a value of type Person you can use @FacesConverter(forClass=Person.class). Look here.

..., whenever that class is specified by a value attribute of an input component, the converter is invoked automatically

Upvotes: 2

Related Questions