从未调用过转换器方法getAsObject()getAsString()

时间:2019-07-04 13:18:48

标签: jsf primefaces converters selectcheckboxmenu

转换无效。 这是我的xhtml之上的代码(目前,我只需要列出所有值):

<p:selectCheckboxMenu id="autoriRicerca"
                        value="#{ricercaLibroBean.autoriRicerca}" 
                        converter="autoriConverter"
                        multiple="true" filter="true" filterMatchMode="startsWith"
                        panelStyle="width:250px">

这是我的转换器:

@FacesConverter("autoriConverter")
public class AutoriCoverter implements Converter {
    @Inject
    private AutoriDAO userService;

    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {

         if (submittedValue == null || submittedValue.isEmpty()) {
                return null;
            }

            try {
                return userService.getListaAutori();//return the lis about  authors
            } catch (NumberFormatException e) {
                throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
            }

    }

    public String getAsString(FacesContext context, UIComponent component, Object object) {
        if (object == null) {
            return "";
        }
        if (object instanceof Autori) {
            Autori autore = (Autori) object;
            String nomeAutore = autore.getNomeAutore();
            return nomeAutore;
        } else {
            throw new ConverterException(new FacesMessage(object + " is not a valid car"));
        }
    } 
}

我的豆子中有:

private List<Autori> autoriRicerca; // and get and set method

Autori有一个(id,nameAuthor).

我不知道这是问题所在。似乎代码没有输入到converter方法中。我已经放置了一些breackpoint,它们不会在调试中执行。有人帮我吗?

1 个答案:

答案 0 :(得分:-1)

在FacesConverter的public Object getAsObject中,您必须返回给定提交ID而不是完整列表的单个Object。

public String getAsString中,您必须返回给定对象的对象ID。

例如

public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {

     if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.getAutoreByID(Long.valueOf(submittedValue));//return the author by id
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }

}

public String getAsString(FacesContext context, UIComponent component, Object object) {
    if (object == null) {
        return "";
    }
    if (object instanceof Autori) {
        Autori autore = (Autori) object;
        Long autoreID = autore.getID();
        return autoreID;
    } else {
        throw new ConverterException(new FacesMessage(object + " is not a valid user"));
    }
}