2012-02-03 37 views
0

我遇到了表单问题。该表格允许用户在一些文本框中输入信息,然后有2个按钮 - 搜索和重置。单击运行清除表单的JS函数的按钮后无法恢复视图

表单代码:

<h:outputText value="Search by Author Name" styleClass="p" /> 

<div class="investigatorTab"> 

    <h:outputLabel for="firstName" rendered="true" value="First Name" /> 
    <h:inputText value="#{pubBacker.firstName}"></h:inputText> 

    <h:outputLabel for="lastName" rendered="true" value="Last Name" /> 
    <h:inputText value="#{pubBacker.lastName}"></h:inputText> 

</div> 

<div class="buttons"> 
    <p:commandButton value="Submit" styleClass="submitButton" action="#{pubBacker.submit}" update="tabs" /> 
    <p:commandButton value="Reset" type="button" actionListener="#{pubBacker.clearEntries}" onclick="clearForm(this.form);" /> 
</div> 

我遇到的问题是,如果我点击搜索按钮,它带我到结果页面,如果我回到搜索页面,它仍然有我在文本字段中搜索的数据,因为这个bean是会话范围的。我希望能够点击重置按钮并清除文本字段中的数据。

目前与下面的代码,如果我点击Reset按钮,搜索按钮不再起作用,并在Firebug控制台它给了我这个错误

<?xml version='1.0' encoding='UTF-8'?> 
<partial-response><error><error-name>class javax.faces.application.ViewExpiredException</error-name><error-message><![CDATA[viewId:/ccadmin/pubManagement.xhtml - View /ccadmin/pubManagement.xhtml could not be restored.]]></error-message></error></partial-response> 

如果我从第二p:commandButton删除onclick="clearForm(this.form);",表单工作正常。

任何想法为什么调用JS函数会使视图到期?

出版豆:

@ManagedBean(name="pubBacker") 
@SessionScoped 
public class Publication { 

    public Publication() {} 

    public void clearEntries() { 
     new Publication(); 
    } 
} 

回答

1

你显然通过form.elements盲目循环清除形式的所有元素。通过这种方式,JSF自动包含的隐藏输入字段也将被清除,因此JSF将检索一个空值,并且它将无法在服务器端找到关联的视图状态。这最终将以ViewExpiredException结束。

我建议只使用JS来清除表单,但只有JSF。如果你有一个代表形式的模型,它会更容易。

<div class="investigatorTab"> 
    <h:outputLabel for="firstName" rendered="true" value="First Name" /> 
    <h:inputText value="#{pubBacker.pub.firstName}"></h:inputText> 

    <h:outputLabel for="lastName" rendered="true" value="Last Name" /> 
    <h:inputText value="#{pubBacker.pub.lastName}"></h:inputText> 
</div> 

<div class="buttons"> 
    <p:commandButton value="Submit" styleClass="submitButton" action="#{pubBacker.submit}" update="tabs" /> 
    <p:commandButton value="Reset" action="#{pubBacker.clear}" process="@this" update="@form" /> 
</div> 

(注意process="@this",这不会处理表单的输入值,因此不对其进行验证)

public void clear() { 
    pub = new Pub(); 
} 
+0

我已经编辑我的问题与样本我的pubBacker。这可能是一个愚蠢的问题,但是如果我从来没有通过调用'Publish pub = new Publication();'来实例化我的pubBacker bean,在我的clearEntries方法中只是说'new Publication()'是正确的吗? – Catfish 2012-02-03 20:36:39

+0

我想你不理解我。查看''组件的值。如果你不想从控制器中提取模型,那么在clear方法中只需'firstName = lastName = null;'也是可以的,但是如果你有很多这样的方法,这很麻烦。 – BalusC 2012-02-03 20:44:37

+0

哦,我以前没有看到修改过的inputText。由于我只有少量的字段,所以我只是将我的变量设置为“”,但是我没有的是'update =“@form”',并且如果我在commandButton上设置了'type',它没有工作。 – Catfish 2012-02-03 20:55:07