gpt4 book ai didi

jsf - 验证失败时 PF 自动完成显示错误的标签

转载 作者:行者123 更新时间:2023-12-04 11:58:09 26 4
gpt4 key购买 nike

我对 primefaces 的 autocomplete 有一个奇怪的行为。

当我提交没有验证错误或其他表单字段有错误的表单时,该组件工作正常。但是,如果自动完成验证失败,标签将替换为项目 @Id 字段。

我怀疑我使用的转换器有问题。基本上,转换器所做的是获取实体的 @Id 值,并将实际实体插入组件的属性映射中,并将 @Id 值作为其键。

这是我的 xhtml:

                            <p:autoComplete
id="autoComp"
value="#{action.timeTable}"
completeMethod="#{action.timeTables}"
var="tt"
itemLabel="#{tt.description}"
itemValue="#{tt}"
dropdown="true"
minQueryLength="3"
forceSelection="true"
converter="entityConverter"
size="30"
required="true"
maxResults="10">

<f:validator validatorId="customValidator" />

</p:autoComplete>

这是我的转换器代码:

@FacesConverter("entityConverter")
public class EntityConverter implements Converter {
@Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
if (value != null) {
return component.getAttributes().get(value);
}

return null;
}

@Override
public String getAsString(FacesContext ctx, UIComponent component, Object obj) {

if (obj instanceof String) {
return obj.toString();
}

if (obj != null) {
String id;

try {
id = this.getId(getClazz(ctx, component), obj);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new ConverterException("msg");
}

id = id.trim();

component.getAttributes().put(id, getClazz(ctx, component).cast(obj));

return id;

}
return null;
}

private Class<?> getClazz(FacesContext facesContext, UIComponent component) {
//get entity's class
}

private String getId(Class<?> clazz, Object obj) throws NoSuchFieldException, IllegalAccessException {
// get entity's ID value
}

}

最佳答案

您的转换器是正确的,因为失败的验证不会触发值的转换,并且 PrimeFaces p:autoComplete 使用提交的值在验证失败时显示,而不是之前设置的正确值。我们通过替换

来更改 AutoCompleteRenderer 来解决此问题
if(ac.isValid()) {
requestMap.put(var, ac.getValue());
itemLabel = ac.getItemLabel();
}
else {
Object submittedValue = ac.getSubmittedValue();
itemLabel = (submittedValue == null) ? null : String.valueOf(submittedValue);

if(itemLabel == null && ac.getValue() != null) {
requestMap.put(var, ac.getValue());
itemLabel = ac.getItemLabel();
}
}

if(ac.isValid()) {
requestMap.put(var, ac.getValue());
itemLabel = ac.getItemLabel();
}
else {
// Display label of previously set value if validation fails
itemLabel = ac.getItemLabel();

if(itemLabel == null && ac.getValue() != null) {
requestMap.put(var, ac.getValue());
itemLabel = ac.getItemLabel();
}
}

关于jsf - 验证失败时 PF 自动完成显示错误的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18315964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com