【问题标题】:Update managed bean with ajax ignoring the required使用 ajax 更新托管 bean,忽略所需
【发布时间】:2013-10-10 15:11:15
【问题描述】:

我想在每次更改selectOneMenu 的值时更新idOutput,但是当它一次更改为与null 不同的值时,我无法再次分配null,我认为是由于required="true",但我不知道如何避免仅在ajax请求中进行验证。

代码如下:

豆子:

@ViewScoped
@ManagedBean
public class ProbeNull implements Serializable
{
    private static final long serialVersionUID = 1628174277372407129L;
    private Boolean probe;
    public ProbeNull()
    {
        super();
    }
    public void show()
    {
        System.err.println("Value : " + probe);
    }
    public void save()
    {
        System.err.println("Save : " + probe);
    }
    public Boolean getProbe()
    {
        return probe;
    }
    public void setProbe(Boolean probe)
    {
        System.err.println("Setter: " + probe);
        this.probe = probe;
    }
}

xhtml:

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">
        <h:head />
        <h:body>
            <h:outputText id="idOutput" value="#{probeNull.probe}" />
            <h:form id="form">
                <p:selectOneMenu id="select" required="true" value="#{probeNull.probe}">
                    <f:selectItem itemLabel="Select one" itemValue="#{null}" />
                    <f:selectItem itemLabel="Yes" itemValue="true" />
                    <f:selectItem itemLabel="No" itemValue="false" />
                    <p:ajax update=":idOutput" />
                </p:selectOneMenu>
                <p:commandButton value="Save" ajax="false" action="#{probeNull.save()}" />
            </h:form>
            <h:form>
                <p:commandButton value="Show value" ajax="false" action="#{probeNull.show()}" />
            </h:form>
        </h:body>
    </html>

如何避免?

【问题讨论】:

  • 为什么要分配null?
  • 这是我的代码的简化版本,我想获取 Boolean 值以根据值在树上添加不同的值节点,或者如果它为空则不添加任何内容。跨度>
  • 如果未选择任何内容,该选项将为 null。一旦选择了某些东西,为什么要将其设置回 null 并破坏用户所做的选择?如果您希望用户能够进行“无选择”,那么您不应将该字段设为必填。
  • 不,我不希望用户在提交表单时选择了Select one 选项,但我想始终使用托管 bean 值更新idOutput(由 ajax on selectOneMenu 中的每次更改。

标签: jsf-2 primefaces


【解决方案1】:

您可以使用两个 remoteCommand 标签和 JavaScript 来做您想做的事。

<p:remoteCommand name="makeSelection" process="select" update=":idOutput" />
<p:remoteCommand name="clearSelection" process="@this" update="select,:idOutput" >
    <f:setPropertyActionListener value="#{null}" target="#{probeNull.probe}" />  
</p:remoteCommand>

现在您可以决定使用 javascript 函数调用哪一个

<p:selectOneMenu id="select" required="true" value="#{probeNull.probe}" onchange="selectFunction(this)">
...

function selectFunction(el){
    //if el.value is empty you call clearSelection();
    //else you call makeSelection();
}

别忘了删除&lt;p:ajax update=":idOutput" /&gt;

【讨论】:

    猜你喜欢
    • 2014-06-10
    • 2012-05-18
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多