Focus manages the element focus of a page. By default the first visible and enabled input receives the focus, for declares the component explicitly and context, as used here, limits the search to a part of the page. After a failed validation the first invalid input receives the focus, which requires that p:focus is updated by the Ajax request.
<div class="card">
<h:form>
<p:focus context="panel"/>
<p:messages/>
<h:panelGroup id="panel" layout="block" styleClass="formgrid grid p-fluid">
<div class="field col-12 md:col-6">
<p:outputLabel for="username" value="Username"/>
<p:inputText id="username" value="#{focusView.username}" required="true" label="Firstname">
<f:validateLength minimum="2"/>
</p:inputText>
<p:message for="username"/>
</div>
<div class="field col-12 md:col-6">
<p:outputLabel for="email" value="Email"/>
<p:inputText id="email" value="#{focusView.email}" required="true" label="Surname"/>
<p:message for="email"/>
</div>
</h:panelGroup>
<p:commandButton id="submitButton" value="Save" update="@parent" action="#{focusView.save}" styleClass="mt-3" />
</h:form>
</div>
package org.primefaces.showcase.view.misc;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.inject.Named;
@Named
@RequestScoped
public class FocusView {
private String username;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void save() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "User Saved"));
username = null;
email = null;
}
}