1

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>
pL4Gu33
  • 2,045
  • 16
  • 38

2 Answers2

2

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
user1983983
  • 4,793
  • 2
  • 15
  • 24
1

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

Community
  • 1
  • 1
Makky
  • 17,117
  • 17
  • 63
  • 86
  • That is a solution, i searched for (the Link). Very big thanks :) – pL4Gu33 Mar 05 '14 at 17:00
  • 1
    @pL4Gu33 Just to let you know that SelectItemsConverter is not for auto complete.Omnifaces has a different converter for that but that has some problems. So , for autocomplete use the one in the link. – Makky Mar 05 '14 at 17:31