我有以下页面/ bean结构(使用myfaces 2.0.11 + tomcat 6)
我有一个复选框,当选中h:inputtext
(它连接到我的bean中的Integer
变量)时,启用了当复选框未选中时输入被禁用,我有一个提交按钮,提交它们(整个表格)
这是代码
<h:form prependId="false">
<h:selectBooleanCheckbox id="my_len" value="#{myBean.myLenBool}">
<f:ajax render="my_len_input_wrapper"/>
</h:selectBooleanCheckbox>
<h:panelGroup id="my_len_input_wrapper">
<h:inputText value="#{myBean.myLen}" id="my_len_input"
disabled="#{not myBean.myLenBool}" required="#{myBean.myLenBool}">
<f:validateLongRange minimum="1"/>
</h:inputText>
<h:message for="my_len_input"/>
</h:panelGroup>
<h:commandButton action="#{myBean.submit}" value="submit">
<f:ajax render="@form" execute="@form"></f:ajax>
</h:commandButton>
</h:form>
Bean代码
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class myBean {
Integer myLen;
boolean myLenBool;
public Integer getMyLen() {
return myLen;
}
public void setMyLen(Integer myLen) {
this.myLen = myLen;
}
public boolean isMyLenBool() {
return myLenBool;
}
public void setMyLenBool(boolean myLenBool) {
this.myLenBool = myLenBool;
}
public void submit() {
// submit
}
}
方案如下
1)选中复选框(输入将被启用)
2)输入无效值(例如0.5),其无效原因myLen
为Integer
3)点击提交 - &gt;错误消息将显示在h:message
转换错误原因中
4)取消选中该复选框(它将禁用inputtext)
5)点击提交&lt; ---表单未提交转换错误的原因?!?!
所以问题是:如何提交带有转换错误的禁用输入的表单???
到目前为止,我找到的唯一解决方案是编写自己的自定义converter
,如果字段被禁用则忽略转换
@FacesConverter("APCustomConverter")
public class APCustomConverter extends IntegerConverter{
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (component.getAttributes().get("disabled") != null && component.getAttributes().get("disabled").equals(true)) {
return null;
}
Object retValue = super.getAsObject(context, component, value);
return retValue;
}
}
希望找到比我更好的解决方案(使用CustomConverter
),
有点偏离/不那么偏离主题:
这个转换错误最终让我陷入了一个非常烦人的场景:当我使用discard按钮时只有render =“@ form”复选框的状态和输入错误,点击丢弃后 - >复选框保持检查(虽然它不应该导致表单没有真正提交)并且输入被禁用而不是只读导致真正的复选框值为false,当我再次点击提交时,复选框变得非常复杂但是输入得到了自己一个空值(所有这些导致服务器上的空指针异常),所以最终我不得不在丢弃按钮中使用<f:actionListener type="org.omnifaces.eventlistener.ResetInputAjaxActionListener" />
by omnifaces。
答案 0 :(得分:3)
使用 Mojarra 2.1.26 和 MyFaces 2.0.11 进行测试。取消选中该复选框后,Mojarra会更新h:inputText
并将其留空,这是预期的行为,因为该值从未到达模型(验证错误)。但是,MyFaces仅将其更新为禁用模式,将旧输入值保留在那里。
这似乎是一个MyFaces问题,即使在最新的(2.1.12-2.0.18)分支版本中也没有解决。事实上,如果你想根据其状态跳过一些元素的转换/验证,那么编写一个自定义转换器/验证器是可行的方法,但在你的情况下,这个问题与MyFaces的ajax循环有关,它应该像Mojarra的一样工作。确实
作为解决方案,您有三种可能的选择: