p:全局实体转换器的自动完成

时间:2014-02-17 19:09:56

标签: primefaces autocomplete converter

我想构建一个p:autocomplete,用于从实体中搜索不同的对象。 像顾客,文章......

搜索效果很好,实体会出现。 但转换器仍无效。

这是我的代码:

<p:autoComplete id="searchStartpage" size="35" maxlength="200"
                                    queryDelay="0" maxResults="10" minQueryLength="1"
                                    value="#{searchGeneralRequestController.selectedObject}"
                                    completeMethod="#{searchGeneralRequestController.completeObject}"
                                    var="o" itemLabel="#{object.id}" itemValue="#{object}"
                                    converter="objectForSearchConverter" forceSelection="false"
                                    itemtipMyPosition="left center" cache="false"
                                    itemtipAtPosition="right center">

                                    <p:ajax event="itemSelect"
                                        listener="#{searchGeneralRequestController.handleSelect}" />

                                    <p:column rendered="#{o.getClass().getSimpleName() == 'Mandatory'}">  
                                        #{o.surname} #{o.name}
                                    </p:column>

                                    <p:column rendered="#{o.getClass().getSimpleName() == 'Article'}">  
                                        #{o.name}
                                    </p:column>

                                </p:autoComplete>

这是我的转换器:

public Object getAsObject(FacesContext facesContext, UIComponent component,
        String submittedValue) {
    if (submittedValue.trim().equals("")) {
        return null;
    } else {
        try {
            // searchValue = submittedValue;
            int number = Integer.parseInt(submittedValue);

            for (Object p : objectList) {

                if (p instanceof Article) {
                    Article article = (Article) p;
                    if (article.getId() == number) {
                        return p;
                    }
                }

                if (p instanceof Customer) {
                    Customer customer = (Customer) p;
                    if (customer.getId() == number) {
                        return p;
                    }
                }

                if (p instanceof User) {
                    User user = (User) p;
                    if (user.getId() == number) {
                        return p;
                    }
                }

                if (p instanceof Mandatory) {
                    Mandatory mandatory = (Mandatory) p;
                    if (mandatory.getId() == number) {
                        return p;
                    }
                }
            }

        } catch (NumberFormatException exception) {
            throw new ConverterException(new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "Conversion Error",
                    "Not a valid player"));
        }
    }

    return null;
}

@Override
    public String getAsString(FacesContext context, UIComponent component,
            Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            Long id = (value instanceof Mandatory) ? ((Mandatory) value)
                    .getId() : null;
            return (id != null) ? String.valueOf(id) : null;
        }
    }

我的所有实体都有哈希和字符串方法。 Object值始终为null

请有人帮忙吗

2 个答案:

答案 0 :(得分:4)

AutoComplete试试此generic converter

import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

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

    private static Map<Object, String> entities = new WeakHashMap<Object, String>();

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object entity) {
        synchronized (entities) {
            if (!entities.containsKey(entity)) {
                String uuid = UUID.randomUUID().toString();
                entities.put(entity, uuid);
                return uuid;
            } else {
                return entities.get(entity);
            }
        }
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
        for (Entry<Object, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
        return null;
    }

}

答案 1 :(得分:0)

这是我的ManagedBean代码:

@Override
    public Object getRowData(String rowKey) {
        List<Object> countries = (List<Object>) getWrappedData();

        for (Object searchGeneral : countries) {

            if (searchGeneral instanceof Mandatory) {
                Mandatory mandatory = (Mandatory) searchGeneral;
                if (mandatory.getId().equals(rowKey))
                    return searchGeneral;
            }

            if (searchGeneral instanceof Article) {
                Article article = (Article) searchGeneral;
                if (article.getId().equals(rowKey))
                    return searchGeneral;
            }

            if (searchGeneral instanceof Customer) {
                Customer customer = (Customer) searchGeneral;
                if (customer.getId().equals(rowKey))
                    return searchGeneral;
            }
        }
        return null;
    }

    @Override
    public Object getRowKey(Object searchGeneral) {

        if (searchGeneral instanceof Customer) {
            Mandatory mandatory = (Mandatory) searchGeneral;
            return mandatory.getId();
        }

        if (searchGeneral instanceof Customer) {
            Customer customer = (Customer) searchGeneral;
            return customer.getId();
        }

        return null;
    }

    public List<Object> completeObject(String query)
            throws SearchGeneralNotFoundException, UserNotFoundException {
        List<Object> suggestions = new ArrayList<Object>();

        query = query.trim();

        filteredSearchGeneral = searchGeneralService.searchForStartPage(query);

        for (Object p : filteredSearchGeneral) {

            if (p instanceof Article) {
                Article article = (Article) p;
                if (article.getName().toLowerCase()
                        .startsWith(query.toLowerCase()))
                    suggestions.add(p);
            }

            if (p instanceof Customer) {
                Customer customer = (Customer) p;
                if (customer.getName().toLowerCase()
                        .startsWith(query.toLowerCase()))
                    suggestions.add(p);
            }

            if (p instanceof Mandatory) {
                Mandatory mandatory = (Mandatory) p;
                if (mandatory.getSurname().toLowerCase()
                        .startsWith(query.toLowerCase()))
                    suggestions.add(p);
                if (mandatory.getName().toLowerCase()
                        .startsWith(query.toLowerCase()))
                    suggestions.add(p);
            }

            if (p instanceof User) {
                User user = (User) p;
                if (user.getName().startsWith(query))
                    suggestions.add(p);
            }

        }

        return suggestions;
    }

    public void handleSelect(SelectEvent event) {
        Object object = (Object) event;
        LOGGER.info("handleSelect: " + object.getClass().getName());

        if (event.getClass().getSimpleName() == "Article") {
            LOGGER.info("ARTICLE");
        }

        redirectToCorrectPage(object);
    }

    public String redirectToCorrectPage(Object object) {
        LOGGER.info("redirectToCorrectPage");

        String url = "";
        FacesContext ctx = FacesContext.getCurrentInstance();

        try {
            if (selectedObject instanceof Mandatory) {
                LOGGER.info("redirectToCorrectPage Mandatory");
                ExternalContext extContext = ctx.getExternalContext();
                url = extContext
                        .encodeActionURL(ctx
                                .getApplication()
                                .getViewHandler()
                                .getActionURL(ctx,
                                        "/portal/mandatoryRegionEdit.xhtml"));
                extContext.redirect(url);
            }
        }

        catch (IOException ioe) {
            throw new FacesException(ioe);
        }

        return url;
    }