我希望我的网页专注于需要更多操作的字段。我按照this示例来实现它,它使用<p:focus context="panel"/>
标记完美运行。如果有任何字段需要值且为空,它将自动关注该特定字段。
当我想从bean设置焦点时,问题出现了。我使用<p:focus id="focusID" for="#{yourBean.focusProperty}" />
关注this来设置焦点,但是有效,但第一个标记<p:focus context="panel"/>
不再有效。这意味着当必填字段为空时,它不会关注该字段,而是始终关注表单的第一个字段。以下是我的代码:
<p:panel id="formPanel" header="Register">
<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" globalOnly="true" />
<p:focus context="formPanel" />
<h:form>
<p:focus id="focusID" for="#{registerBean.focusProperty}"/>
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="name" value="Name: " />
<p:inputText id="name" value="#{registerBean.profile.name}" required="true"/>
<p:message for="name"/>
<p:outputLabel for="tp" value="TP: " />
<p:inputText id="tp" value="#{registerBean.student.tp}" required="true"/>
<p:message for="tp"/>
<p:outputLabel for="email" value="Email: " />
<p:inputText id="email" value="#{registerBean.account.email}" required="true"/>
<p:message for="email"/>
<p:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{registerBean.account.username}" required="true"/>
<p:message for="username"/>
<p:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{registerBean.account.password}" required="true" />
<p:message for="password"/>
<p:outputLabel for="confirmPassword" value="Confirm Password: " />
<p:password id="confirmPassword" value="#{registerBean.confirmPassword}" required="true" />
<p:message for="confirmPassword"/>
<p:commandButton value="Register" action="#{registerBean.register()}" update="formPanel"/>
</h:panelGrid>
</h:form>
</p:panel>
RegisterBean.java
public String register()
{
System.out.println("register");
String accountValidateResult = accountService.validate(account);
String studentValidateResult = studentService.validate(student);
System.out.println("Validation Result: " + accountValidateResult);
if (!studentValidateResult.isEmpty())
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", studentValidateResult + " has been taken"));
focusProperty = studentValidateResult.toLowerCase();
return null;
}
if (!accountValidateResult.isEmpty())
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", accountValidateResult + " has been taken"));
focusProperty = accountValidateResult.toLowerCase();
return null;
}
profile = profileService.insert(profile);
account.setProfileId(profile.getId());
student.setProfileId(profile.getId());
accountService.insert(account);
studentService.insert(student);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Registration Successful", "Please login to you account"));
FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
return "index?faces-redirect=true";
}