【发布时间】:2020-03-23 11:50:38
【问题描述】:
我正在使用 Bootsfaces 来显示模式对话框。在模态对话框中有一个字段(实际上是b:inputTextarea)和一个使用Ajax 提交数据的命令按钮。我想确保用户在提交之前在文本字段中输入了一些内容。如果该字段为空,则不应关闭模式并且不应发生提交,如果该字段为非空,则应关闭对话框并且应以 Ajax 样式进行提交。
由于带有 Bootsfaces 1.4.2 的 issue,我不能使用 b:command 来执行 Ajax 部分。我必须使用h:commandButton 和f:ajax 的标准方式。
我正在尝试这样解决我的问题:
<b:form>
<!-- section that gets updated by ajax-request -->
<b:panel id="updateSection">
<h:outputText value="#{testBean.value1}" />
<b:button value="open dialog" onclick="$('.pseudoClass').modal()" />
</b:panel>
<!-- modal dialog -->
<b:modal title="model" styleClass="pseudoClass" closable="false" closeOnEscape="true">
<b:panel id="modalOutput"><h:inputText value="#{testBean.value1}" /></b:panel>
<f:facet name="footer">
<!-- cancel button -->
<b:button largeScreen="half" value="cancel" dismiss="modal" onclick="return false;" />
<!-- submit button ajax-style -->
<h:commandButton value="submit" action="#{testBean.save()}" onclick="validateModalDialog();">
<f:ajax render="updateSection" execute="@this modalOutput" onevent="closeModalDialog" />
</h:commandButton>
<!-- scripts to close & validate modal dialog -->
<h:outputScript>
function closeModalDialog(data) {
var status = data.status;
if (status === 'complete') { $('.pseudoClass').modal('hide'); }
}
function validateModalDialog() {
alert('i get called before closing dialog');
return false;
}
</h:outputScript>
</f:facet>
</b:modal>
</b:form>
脚本函数validateModalDialog 在模态对话框关闭之前被调用,但无论函数的返回值如何(true 或 false),对话框都会关闭。
我对 JavaScript 的了解相当有限。这也是我选择使用 JSF 和 Bootsfaces 的原因之一。但我很确定有办法进行验证并防止对话框关闭。
在使用标准组件 h:commandButton 和 f:ajax 时,如何模拟 Bootsfaces 功能(模式对话框中文本字段的客户端验证)?
解决方案:
为了实现客户端验证,防止 Ajax 请求触发和模式对话框关闭,与我的初始代码相比,需要进行以下更改:
<h:commandButton value="submit" action="#{testBean.save()}" onclick="return validateModalDialog();">
<f:ajax render="updateSection" execute="@this modalOutput" onevent="closeModalDialog" />
</h:commandButton>
【问题讨论】:
-
不幸的是,我不能使用 Bootsfaces 中的
b:commandButton,但必须使用没有oncomplete属性的标准组件h:commandButton。所以挑战是在不使用b:commandButton的情况下模拟 Bootsfaces 功能。 -
幸运的是,您可以使用
f:ajax onevent模拟oncomplete事件:ajax call in jsf 2.0 (myfaces), the onevent Javascript function in the ajax tag gets called before the rendering is complete -
我正在使用
onevent,如您在上面的代码示例中所见。但是如何阻止 Ajax 请求得到实际处理呢?目标是在验证失败(字段为空)的情况下不关闭模式对话框并且不发出 Ajax 请求。
标签: ajax jsf bootsfaces