How to recharge a primefaces component after successful login with ajax behaviour - ajax

I am trying to recharge the same primefaces component after an successful login with ajax behaviour, but I don't know how to do this. The recharged component must show the complete name of the user which is recovered by an hibernate dao from the DB and the input boxes for user and password must desappear.
View :
<h:head>
<title>header layout</title>
</h:head>
<h:body>
<h:panelGrid id="loginPanelGrid">
<h:form id="loginForm">
<h:outputLabel for="username" value="Username:" />
<p:inputText value="#{loginManagedBean.username}" id="username" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<p:password value="#{loginManagedBean.password}" id="password" required="true" label="password" />
</h:form>
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" update="okLoginPanelGrid" action="#{loginManagedBean.login(actionEvent)}"/>
</f:facet>
</h:panelGrid>
<p:panelGrid id="okLoginPanelGrid">
<h:outputText id="clienteLogado" value="#{loginManagedBean.loggedClient}" />
</p:panelGrid>
</h:body>
Bean :
#ManagedBean
#SessionScoped
public class LoginManagedBean implements Serializable{
private String username;
private String password;
private Cliente loggedClient;
#ManagedProperty(value="#{clienteDAO}")
private ClienteDAO clienteDAO;
public void login(ActionEvent actionEvent){
RequestContext context = RequestContext.getCurrentInstance();
if( (this.getUsername() != null && !this.getUsername().isEmpty()) &&
(this.getPassword() != null && !this.getPassword().isEmpty()) ){
List<Cliente> clienteLogin = clienteDAO.comprobarLogin(username, password);
if(clienteLogin != null && clienteLogin.size() > 0){
loggedClient = new Cliente();
for(Cliente client : clienteLogin){
loggedClient.setCliente_nombre(client.getCliente_nombre());
loggedClient.setCliente_apellido1(client.getCliente_apellido1());
loggedClient.setCliente_apellido2(client.getCliente_apellido2());
}
}else{
System.out.println("**** There are NO CLIENTS for this user and password selected ****");
}
}else{
System.out.println("**** user or password NOT RECOVERED ****");
}
}

You should move your h:form to encapsulate the p:commandButton. That prevent your p:commandButton to submit anything to the bean. You should add it like this :
<h:body>
<h:panelGrid id="login-panel">
<h:form rendered="#{loginManagedBean.loggedClient eq null}">
<h:panelGroup id="loginPanelGrid">
<h:outputLabel for="username" value="Username:" />
<p:inputText value="#{loginManagedBean.username}" id="username" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<p:password value="#{loginManagedBean.password}" id="password" required="true" label="password" />
<f:facet name="footer">
<p:commandButton id="loginButton" value="Login" update="login-panel" action="#{loginManagedBean.login(actionEvent)}"/>
</f:facet>
</h:panelGroup>
</h:form>
<p:panelGroup rendered="#{loginManagedBean.loggedClient ne null}" id="okLoginPanelGrid">
<h:outputText id="clienteLogado" value="#{loginManagedBean.loggedClient.client_name}" />
</p:panelGroup>
</h:panelGrid>
</h:body>
Not related :
I would also say the shorter a bean lives, the better your memory usage will be. In that way, the bean LoginManagedBean don't need to be SessionScoped, it could even be only RequestScoped if you move your property loggedClient to a SessionScoped attribute.

Related

p:selectOneMenu not keeping value after form validation

I want to keep selected values after form validation. My code is here:
<h:form id="advanceSearchForm">
<p:dataGrid value="#{advancedSearchBean.selectedCriteriasList}" id="advancedSearchGrid" var="criteria" rowIndexVar="rowIndex"
columns="2" layout="grid" paginator="false" >
<h:panelGrid columns="1" id="criteriaPanel">
<p:panel id="criteria">
<div>
<!-- select criteria -->
<p:selectOneMenu value="#{criteria}" label="#{criteria.name}"
valueChangeListener="#{advancedSearchBean.addNewCriteria}"
converter="#{advancedSearchBean.criteriaConverter}">
<f:selectItems value="#{advancedSearchBean.criterias}"
var="crt"
itemLabel="#{crt.name}"
itemValue="#{crt}"
itemDisabled="#{advancedSearchBean.disableItem(crt.id)}" />
<f:ajax execute="#this"/>
</p:selectOneMenu>
<!-- launch date -->
<p:outputPanel rendered="#{criteria.id != null and (criteria.id == BusinessConstants.ADVANCED_SEARCH_FILTER_LAUNCH_DATE_ID)}">
<p:outputPanel>
<h:outputText value="From" styleClass="passportLabel" />
<p:inputMask required="true" id="launchStartDate" value="#{advancedSearchBean.launchStartDate}" mask="99/9999">
<f:convertDateTime pattern="MM/yyyy" timeZone="#{sessionScope.identity.timezone}" />
<p:ajax event="change" listener="#{advancedSearchBean.changeLaunchStartDate()}" />
</p:inputMask>
</p:outputPanel>
<p:outputPanel>
<h:outputText value="To" styleClass="passportLabel" />
<p:inputMask required="true" id="launchEndDate" value="#{advancedSearchBean.launchEndDate}" mask="99/9999">
<f:convertDateTime pattern="MM/yyyy" timeZone="#{sessionScope.identity.timezone}" />
<p:ajax event="change" listener="#{advancedSearchBean.changeLaunchEndDate()}" />
</p:inputMask>
</p:outputPanel>
</p:outputPanel>
</div>
</p:panel>
</h:panelGrid>
</p:dataGrid>
<!-- run search button -->
<div>
<p:commandButton id="runAdvancedSearch" value="Run search" action="#{advancedSearchBean.doAdvancedSearch}"
update="advanceSearchForm:advancedSearchGrid"/>
</div>
</h:form>
When i'm typing a wrong date and click on the Search button, i'm getting my validation error message, and i'm also losing the selected value in the selectOneMenu.
The strange thing is that if redirect to another page and after that i'm coming back, it works... My bean is:
#ManagedBean(name = "advancedSearchBean")
#ViewScoped
public class AdvancedSearchBean {
private Map<Long, String> criteriaMap;
private List<AutocompleteCriteria> criterias;
private List<AutocompleteCriteria> selectedCriteriasList;
#PostConstruct
public void init() {
criteriaMap = BusinessConstants.ADVANCED_SEARCH_CRITERIA.entrySet().stream().sorted(Entry.comparingByValue()).
collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
criterias = new ArrayList<AutocompleteCriteria>();
for(Iterator<Map.Entry<Long, String>>it = criteriaMap.entrySet().iterator();it.hasNext();){
Map.Entry<Long, String> entry = it.next();
criterias.add(new AutocompleteCriteria(entry.getKey(), entry.getValue()));
}
criteriaConverter = new AutocompleteConverter(criterias);
selectedCriteriasList = new ArrayList<AutocompleteCriteria>();
selectedCriteriasList.add(new AutocompleteCriteria(BusinessConstants.ADVANCED_SEARCH_FILTER_NO_CRITERIA, criteriaMap.get(BusinessConstants.ADVANCED_SEARCH_FILTER_NO_CRITERIA)));
}
In your p:selectOneMenu You have value="#{criteria}" instead of value="#{advancedSearchBean.criteria}".

Method in actionListener is not invoked after validation failed

I have a command Button that calls a method from the Session Scoped Bean if the inputs are valid.
<h:form id="mainform">
<p:panel id="panelform" header="Email Extractor" >
<h:panelGrid id="formulaire" columns="2">
<h:panelGroup id="formblock" layout="block" >
<p:panelGrid columns="2">
<p:outputLabel for="Keyword" value="Keyword: " />
<p:inputText id="Keyword" type="search" requiredMessage="Keyword is required"
value="#{mailMB.keyword}" required="true" label="Keyword">
</p:inputText>
<p:outputLabel for="Emailsnbr" value="Enter the emails'number:" />
<p:inputText id="Emailsnbr" type="number" requiredMessage="Emails number is required" validatorMessage="Enter a number"
value="#{mailMB.number}" required="true" label="Emailsnbr">
<f:validateDoubleRange minimum="1" maximum="53500" />
</p:inputText>
</p:panelGrid>
</h:panelGroup>
</h:panelGrid>
<p:commandButton value="Extract" style="width: 12%;height: 100%" update="tableemails, :confirmPurchaseTest, :mainform" id="extractbutton" ajax="true" widgetVar="ButtonExtract"
actionListener="#{mailMB.searchEmails()}" onstart="blockUIWidget1.show();" oncomplete=" blockUIWidget1.hide(); if (args && !args.validationFailed) confirmDialog.show();" />
<p:dialog widgetVar="blockUIWidget1" modal="true" closable="false" resizable="false" >
<h:panelGrid columns="2">
<div>
<p:graphicImage url="pictures/loading81.gif" width="200" height="200" alt="animated-loading-bar"/>
<h:outputLabel value="Please wait..."/>
</div>
<div>
<p:button outcome="home" icon="ui-icon-arrowthick-1-w" title="Back To Home" style="margin-right: 5px;white-space: nowrap" />
</div>
</h:panelGrid>
</p:dialog>
</p:panel>
<p:dataTable rowIndexVar="rowIndex" id="tableemails" value="#{mailMB.mails}" var="item" rowsPerPageTemplate="5,10,15" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
paginator="true" rows="5" styleClass="case-table" emptyMessage="No records found with given criteria" paginatorPosition="bottom"
filteredValue="#{mailMB.filteredMails}" rowKey="#{item.id}"
selection="#{mailMB.selectedMail}" selectionMode="single" >
<p:ajax event="rowSelect" update=":mainform"/>
<p:column styleClass="blockable">
<f:facet name="header">
<h:outputText value="Email"/>
</f:facet>
<h:outputText value="#{item.email}"/>
</p:column>
</p:dataTable>
</h:form>
<p:confirmDialog closable="false" style="position: absolute; width: 50px; border-color: blue" id="confirmPurchaseTest" message="Your Database was successfully created. It contains #{mailMB.number} Emails "
appendToBody="true"
header="Get Emails List" severity="info" widgetVar="confirmDialog">
<h:form>
<p:commandButton id="getEmails" style="width: 35%;height: 100%" value="Get Emails" oncomplete="window.location.href = '/Hitonclick/emailsList.xhtml'" >
<f:event type="preRenderView" listener="#{mailMB.preRender}"/>
</p:commandButton>
<p:commandButton id="declineTest" style="width: 35%;height: 100%" value="Decline" onclick="deleteDialog.show();" />
</h:form>
</p:confirmDialog>
My SessionScoped Bean is
#ManagedBean(name = "mailMB")
#SessionScoped
public class MailManagedBean implements Serializable {
#Inject
private MailBusinessLocal mailmanagerLocal;
#Inject
private DataBusinessLocal dataBusinessLocal;
#Inject
private CustomerBusinessLocal customerBusinessLocal;
.....
#PostConstruct
public void init() {
mails = new ArrayList<>();
}
public void searchEmails() throws Exception {
idCustomer = (String) session.getAttribute("idCustomer");
System.out.println(idCustomer + " this is it");
Customer customer = customerBusinessLocal.findById(idCustomer);
data = dataBusinessLocal.createData(new Date(), number, keyword, moteur, customer, State.REJECTED);
mails = mailBusinessLocal.createEmails(keyword, number, moteur, data);
System.out.println("Method was invoked");
}
}
if i enter 0 in the emails's number input for exemple and submit with Extract command Button for the first time i get the validatorMessage So i enter a valid number and submit again. And here comes the problem, the dialog in the oncomplete is shown without invoking the method in the actionListener. I mean i get the confirm dialog of persisted object without invoking the method that persists the object. Am i missing something??
How could i fix that?

PrimeFaces dialog is validated only the first time it appears

JSF 2.2, PrimeFaces 3.5.
home.xhtml contains a tabview with nested dataTables and add/edit/delete buttons. Each button is supposed to call a dialog with a form and submit/cancel buttons.
The problem is that validation is processed only once (see screenshot) and if I press "Add" / "Cancel" the dialog just hides and no validation is made. And if I try to reopen it once again and input values and hit "Add" - it just skips validation and renders response. So, basically, it just makes a initial request (if I guessed right).
Console output for pressing "Add" with empty values 3 times. First click has been processed the way I want it, but the next ones are just hiding the dialog without any validation:
2014-01-24 17:56:09,590 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RESTORE_VIEW 1
2014-01-24 17:56:09,628 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: APPLY_REQUEST_VALUES 2
2014-01-24 17:56:09,633 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: PROCESS_VALIDATIONS 3
2014-01-24 17:56:09,645 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RENDER_RESPONSE 6
2014-01-24 17:56:13,127 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RESTORE_VIEW 1
2014-01-24 17:56:13,128 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RENDER_RESPONSE 6
2014-01-24 17:56:16,557 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RESTORE_VIEW 1
2014-01-24 17:56:16,558 DEBUG [RequestLoggingPhaseListener] Entering JSF Phase: RENDER_RESPONSE 6
home.xhtml (dialogs are at the bottom of a page):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:component xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ex="http://java.sun.com/jsf/composite/nsobchuk">
<h:head>
<title>Home page</title>
<link rel="stylesheet" href="../css/style.css"/>
</h:head>
<h:body>
<h:form id="logout" class="logout" >
<h:commandButton action="#{loginBean.logout()}" value="logout"/>
</h:form>
<p:tabView id="tab" orientation="left">
<p:tab title="Users">
<h:form id="form1">
<h:panelGrid columns="9">
<p:commandButton type="button" value="Add" onclick="dlg1.show()" />
<p:commandButton id="editUser" type="button" value="Edit" onclick="dlg2.show()" disabled="#{homeBean.selectedUser == null}"/>
<p:dialog id="editUserDialogerDialog" widgetVar="dlg2" header="Sorry" >
<h:outputText value="I didn't have enogh time to finish this functionality. Feel free to test other buttons."/>
</p:dialog>
<p:commandButton id="deleteUser" type="button" onclick="confirmation1.show()" value="Delete" disabled="#{homeBean.selectedUser == null}"/>
<p:confirmDialog message="Are you sure you want to delete user?" header="Confirmation"
severity="alert" widgetVar="confirmation1">
<p:commandButton value="Yes" update=":tab:users" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation1.hide()" action="#{homeBean.deleteUser}" />
<p:commandButton value="No" onclick="confirmation1.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="users" var="user" value="#{homeBean.users}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedUser}" rowKey="#{user.userId}"
sortMode="single">
<p:ajax event="rowSelect" listener="#{homeBean.onUserRowSelect}" update=":tab:form1:deleteUser, :tab:form1:editUser"/>
<p:ajax event="rowUnselect" listener="#{homeBean.onUserRowUnselect}" update=":tab:form1:deleteUser, :tab:form1:editUser"/>
<p:column headerText="Login" sortBy="#{user.login}">
<h:outputText value="#{user.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{user.password}">
<h:outputText value="#{user.password}"/>
</p:column>
<p:column headerText="Role" sortBy="#{user.role}">
<h:outputText value="#{user.role}"/>
</p:column>
<p:column headerText="Name" sortBy="#{user.firstName}">
<h:outputText value="#{user.firstName}"/>
</p:column>
<p:column headerText="Surname" sortBy="#{user.lastName}">
<h:outputText value="#{user.lastName}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:users" fileName="Users"/>
</p:tab>
<p:tab title="Computers">
<h:form id="form2">
<h:panelGrid columns="9">
<p:commandButton type="button" value="Add" onclick="dlg3.show()"/>
<p:commandButton id="editComp" type="button" value="Edit" onclick="dlg4.show()" disabled="#{homeBean.selectedComputer == null}"/>
<p:dialog id="editCompDialog" widgetVar="dlg4" header="Sorry" >
<h:outputText value="I didn't have enogh time to finish this functionality. Feel free to test other buttons."/>
</p:dialog>
<p:commandButton id="deleteComp" type="button" onclick="confirmation2.show()" value="Delete" disabled="#{homeBean.selectedComputer == null}"/>
<p:confirmDialog message="Are you sure you want to delete this computer?" header="Confirmation"
severity="alert" widgetVar="confirmation2">
<p:commandButton value="Yes" update=":tab:computers" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation2.hide()" action="#{homeBean.deleteComputer}"/>
<p:commandButton value="No" onclick="confirmation2.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="computers" var="computer" value="#{homeBean.computers}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedComputer}" rowKey="#{computer.computerId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onCompRowSelect}" update=":tab:form2:editComp, :tab:form2:deleteComp"/>
<p:column headerText="Login" sortBy="#{computer.login}">
<h:outputText value="#{computer.login}"/>
</p:column>
<p:column headerText="Password" sortBy="#{computer.password}">
<h:outputText value="#{computer.password}"/>
</p:column>
<p:column headerText="Name" sortBy="#{computer.computerName}" >
<h:outputText value="#{computer.computerName}"/>
</p:column>
<p:column headerText="IP address" sortBy="#{computer.ipAddress}">
<h:outputText value="#{computer.ipAddress}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:computers" fileName="Computers"/>
</p:tab>
<p:tab title="Applications">
<h:form id="form3">
<h:panelGrid columns="9">
<p:commandButton type="button" value="Add" onclick="dlg5.show()"/>
<p:commandButton id="editApp" type="button" value="Edit" onclick="dlg6.show()" disabled="#{homeBean.selectedApplication == null}"/>
<p:dialog id="editAppDialog" widgetVar="dlg6" header="Sorry" >
<h:outputText value="I didn't have enogh time to finish this functionality. Feel free to test other buttons."/>
</p:dialog>
<p:commandButton id="deleteApp" type="button" onclick="confirmation3.show()" value="Delete" disabled="#{homeBean.selectedApplication == null}"/>
<p:confirmDialog message="Are you sure you want to delete this application?" header="Confirmation"
severity="alert" widgetVar="confirmation3">
<p:commandButton value="Yes" update=":tab:applications" process="#this" styleClass="ui-confirmdialog-yes" icon="ui-icon-check"
oncomplete="confirmation3.hide()" action="#{homeBean.deleteApplication}"/>
<p:commandButton value="No" onclick="confirmation3.hide()" type="button" styleClass="ui-confirmdialog-no" icon="ui-icon-close"/>
</p:confirmDialog>
</h:panelGrid>
</h:form>
<p:dataTable id="applications" var="app" value="#{homeBean.applications}"
scrollable="true" scrollHeight="250" selectionMode="single"
selection="#{homeBean.selectedApplication}" rowKey="#{app.appId}"
sortMode="single" >
<p:ajax event="rowSelect" listener="#{homeBean.onAppRowSelect}" update=":tab:form3:editApp, :tab:form3:deleteApp"/>
<p:column headerText="Name" sortBy="#{app.appName}">
<h:outputText value="#{app.appName}"/>
</p:column>
<p:column headerText="Vendor" sortBy="#{app.vendorName}" >
<h:outputText value="#{app.vendorName}"/>
</p:column>
<p:column headerText="License required" sortBy="#{app.licenseRequired}">
<h:outputText value="#{app.licenseRequired}"/>
</p:column>
</p:dataTable>
<ex:exporter target=":tab:applications" fileName="Applications" />
</p:tab>
</p:tabView>
<p:dialog id="addUserDialog" header="Add Dialog" modal="true" closable="false"
widgetVar="dlg1" width="620" >
<h:form id="dlg1form">
<h:panelGrid columns="3">
<h:outputLabel for="login" value="Login: "/>
<p:inputText id="login" required="true"
label="Login: " maxlength="20" >
</p:inputText>
<p:message for="login" />
<h:outputLabel for="password" value="Password: "/>
<p:password id="password" required="true"
feedback="true" label="Password: " maxlength="32"/>
<p:message for="password" />
<h:outputLabel for="firstName" value="First Name: "/>
<p:inputText id="firstName"
label="First Name: " maxlength="20"/>
<p:message for="firstName"/>
<h:outputLabel for="lastName" value="Last Name: "/>
<p:inputText id="lastName"
label="Last Name: " maxlength="20"/>
<p:message for="lastName"/>
<h:outputLabel for="role" value="Role: "/>
<p:selectOneMenu id="role" required="true" style="width: 80px;" >
<f:selectItem itemLabel="user" itemValue="ROLE_USER" />
<f:selectItem itemLabel="admin" itemValue="ROLE_ADMIN" />
</p:selectOneMenu>
<p:message for="role"/>
</h:panelGrid>
<p:commandButton value="Cancel" onclick="dlg1.hide()" update="#form">
<p:resetInput target="addUserDialog" />
</p:commandButton>
<p:commandButton value="Add" update="#form" immediate="false"
oncomplete="if (args && !args.validationFailed) dlg1.hide()" />
</h:form>
</p:dialog>
<p:dialog id="addCompDialog" header="Add Dialog" draggable="true" closable="false" modal="true"
widgetVar="dlg3" width="600">
<h:form id="dlg3form">
<h:panelGrid columns="3">
<h:outputLabel for="pclogin" value="Login: "/>
<p:inputText id="pclogin" required="true"
label="Login: " maxlength="20">
</p:inputText>
<p:message for="pclogin"/>
<h:outputLabel for="pcpassword" value="Password: "/>
<p:password id="pcpassword" required="true"
feedback="true" label="Password: " maxlength="32"/>
<p:message for="pcpassword" />
<h:outputLabel for="compName" value="Computer Name: "/>
<p:inputText id="compName" required="true"
label="Computer Name: " maxlength="20"/>
<p:message for="compName"/>
<h:outputLabel for="ipaddress" value="IP address: "/>
<p:inputText id="ipaddress" required="true"
label="IP address: " maxlength="20"/>
<p:message for="ipaddress"/>
</h:panelGrid>
<p:commandButton value="Cancel" immediate="true" onclick="dlg3.hide()" process="#this" update="#form">
<p:resetInput target="addCompDialog" />
</p:commandButton>
<p:commandButton value="Add" update="#form"
oncomplete="if (args && !args.validationFailed) dlg3.hide()" />
</h:form>
</p:dialog>
<p:dialog id="addAppDialog" header="Add Dialog" draggable="true" closable="false" modal="true"
widgetVar="dlg5" width="600" >
<h:form id="dlg5form">
<h:panelGrid columns="3">
<h:outputLabel for="appName" value="Name: "/>
<p:inputText id="appName" required="true"
label="Name: "/>
<p:message for="appName"/>
<h:outputLabel for="vendorName" value="Vendor: "/>
<p:inputText id="vendorName"
label="Vendor: " required="true" />
<p:message for="vendorName"/>
<h:outputLabel for="appLicense" value="Requires license: "/>
<p:selectOneMenu id="appLicense" required="true" style="width: 80px;" >
<f:selectItem itemLabel="True" itemValue="#{true}" />
<f:selectItem itemLabel="False" itemValue="#{false}" />
</p:selectOneMenu>
<p:message for="appLicense"/>
</h:panelGrid>
<p:commandButton value="Cancel" immediate="true" onclick="dlg5.hide()" update="#form" process="#this">
<p:resetInput target="addAppDialog" />
</p:commandButton>
<p:commandButton value="Add" update="#form"
oncomplete="if (args && !args.validationFailed) dlg5.hide()"/>
</h:form>
</p:dialog>
</h:body>
</ui:component>
HomeBean:
#Component
#Scope("session")
public class HomeBean extends BaseBean {
private static final String editUserBtn = "tab:form1:editUser";
private static final String deleteUserBtn = "tab:form1:deleteUser";
private static final String editCompBtn = "tab:form2:editComp";
private static final String deleteCompBtn = "tab:form2:deleteComp";
private static final String editAppBtn = "tab:form3:editApp";
private static final String deleteAppBtn = "tab:form3:deleteApp";
#Autowired
private HibernateDBManager hibernateDBManager;
private List<User> users;
private List<Computer> computers;
private List<Application> applications;
private User selectedUser, newUser;
private Computer selectedComputer, newComputer;
private Application selectedApplication, newApplication;
private RequestContext rc;
#Override
public void init() {
setUsers(hibernateDBManager.getAllUsers());
setComputers(hibernateDBManager.getAllComputers());
setApplications(hibernateDBManager.getAllApplications());
newUser = new User();
newComputer = new Computer();
newApplication = new Application();
rc = RequestContext.getCurrentInstance();
}
public void addUser() throws NoSuchAlgorithmException {
if (newUser != null && newUser.getPassword() != null) {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(newUser.getPassword().getBytes());
String hash = new BigInteger(1, md.digest()).toString(16);
newUser.setPassword(hash);
if (hibernateDBManager.insertUser(newUser)) {
users.add(newUser);
}
}
}
public void editUser() {
if (selectedUser != null) {
hibernateDBManager.updateUser(selectedUser);
users.set(users.indexOf(selectedUser), selectedUser);
selectedUser = null;
rc.update(deleteUserBtn);
rc.update(editUserBtn);
}
}
public void deleteUser() throws IOException {
if (selectedUser != null) {
if (hibernateDBManager.deleteUserById(selectedUser.getUserId()) > 0) {
users.remove(selectedUser);
selectedUser = null;
rc.update(deleteUserBtn);
rc.update(editUserBtn);
}
}
}
public void addComputer() {
if (newComputer != null && hibernateDBManager.insertComputer(newComputer)) {
computers.add(newComputer);
}
}
public void deleteComputer() {
if (selectedComputer != null) {
if (hibernateDBManager.deleteComputerById(selectedComputer.getComputerId()) > 0) {
computers.remove(selectedComputer);
selectedComputer = null;
rc.update(editCompBtn);
rc.update(deleteCompBtn);
}
}
}
public void addApplication() {
if (newApplication != null && hibernateDBManager.insertApplication(newApplication)) {
applications.add(newApplication);
}
}
public void deleteApplication() {
if (selectedApplication != null) {
if (hibernateDBManager.deleteApplicationById(selectedApplication.getAppId()) > 0) {
applications.remove(selectedApplication);
selectedApplication = null;
rc.update(editAppBtn);
rc.update(deleteAppBtn);
}
}
}
public void onUserRowSelect(SelectEvent event) {
setSelectedUser((User) event.getObject());
}
public void onUserRowUnselect(UnselectEvent event) {
setSelectedUser(null);
}
public void onCompRowSelect(SelectEvent event) {
setSelectedComputer((Computer) event.getObject());
}
public void onAppRowSelect(SelectEvent event) {
setSelectedApplication((Application) event.getObject());
}
//Getters etc.
}
I'd like to keep the dialog opened and validated each time user presses "Add" and not only once. Can anybody help me achieve this with my code or point me to the solution? (similar answered question with rating -1 didn't help me) Every answer is highly appreciated.
Thank you all.
Ok, guys. I found a solution by myself. What I did to make it work was giving a panelGrid element inside a form an id an updating panelGrid instead of a whole form.
So, "Add" button was changed to:
<p:commandButton value="Add"
update=":dlg1form:dt, :tab:users"
action="#{homeBean.addUser}"
oncomplete="if (!args.validationFailed) dlg1.hide()" />
and panelGrid, which contains input fields:
<h:form id="dlg1form">
<h:panelGrid columns="3" id="dt">
This helped me to validate input fields on every click and not just once.
Sincerely hope that this will help someone.
Cheers!
I had the same problem : having a update="#form" or update="yourFormName" inside my <p:commandButton> prevented the dialog from being kept when a validation error occured.
This might be due to the fact that including the update form command regenerate the whole dialog but doesn't trigger the dialogWidgetVar.show() js command.
I solved the issue by nesting a <p:fragment autoUpdate="true"> inside the dialog. Then, you can remove the update keyword inside the triggering commandButton since every component inside the fragment will be updated. The result is that the <p:dialog> and </p:dialog> tags are not replaced when the client receives the Ajax response. My working code is as follows :
<h:form id="locations_editer_creer">
<p:dialog id="location_dlg" widgetVar="locationDlg" header="#{msgs.LocationCreerNouvelle}" width="600" dynamic="false" closeOnEscape="true"
minimizable="true" maximizable="true" modal="true" >
<p:fragment autoUpdate="true">
your form inputs e.g. <p:inputText .../>
<p:commandButton id="OK" value="OK"
actionListener="#{locationsControleur.confirmer()}"
oncomplete="traiteRequeteCreationLoc(xhr, status, args)"
styleClass="ui-confirmdialog-yes" icon="ui-icon-check"/>
</p:fragment>
</p:dialog>
</h:form>
This technique is described inside the excellent PrimeFaces Beginner's Guide book by K. Siva Prasad Reddy (Packt Publishing), p. 54 : Partial Processing and Rendering using the Fragment component.
Hope this can help others.

How to handle h:inputText validation?

I'd like to display an error next to the fields that are wrong. I have that code for my page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/WEB-INF/templates/basic.xhtml">
<ui:define name="content">
<h:form>
<h:panelGrid columns="3">
<h:outputText value="Firstname"/>
<h:inputText id="firstName" value="#{account.firstName}" required="true">
<f:validator validatorId="stringAlphaValidator"/>
</h:inputText>
<h:message for="firstName" errorStyle="color:red; display:block"/>
<h:outputText value="Lastname"/>
<h:inputText id="lastName" value="#{account.lastName}" required="true">
<f:validator validatorId="stringAlphaValidator"/>
</h:inputText>
<h:message for="lastName" errorStyle="color:red; display:block"/>
<h:outputText value="Login"/>
<h:inputText id="login" value="#{account.login}" required="true">
<f:validator validatorId="stringAlphaValidator"/>
</h:inputText>
<h:message for="login" errorStyle="color:red; display:block"/>
<h:outputText value="Password"/>
<h:inputText id="password" value="#{account.password}" required="true">
</h:inputText>
<h:message for="password" errorStyle="color:red; display:block"/>
<h:outputText value="Address"/>
<h:inputText id="address" value="#{account.address}" required="true">
<f:validator validatorId="stringAlphaNumericValidator"/>
</h:inputText>
<h:message for="address" errorStyle="color:red; display:block"/>
<h:outputText value="Email"/>
<h:inputText id="email" value="#{account.email}" required="true">
<f:validator validatorId="emailAddressValidator"/>
</h:inputText>
<h:message for="email" errorStyle="color:red; display:block"/>
</h:panelGrid>
<h:commandButton value="Register"/>
<h:messages globalOnly="true"/>
</h:form>
</ui:define>
</ui:composition>
</html>
If a field is empty and I press the Register button, I get that (here all fields are empty):
(sorry the error is in french. I don't know if it comes from my eclipse language or my tomcat server)
I didn't write this ! This is a text that my program writes on it's own somehow... How do I remove this ?
Also, this is a register page, I'd like to add to my DB the user (if the fields are right) and then change of page with the action login. How can I call a method to do that before it changes of page ?
If you need to see more code, like the validator classes, I can add it.
This should work.
<h:inputText id="lastName" value="#{account.lastName}" required="true" requiredMessage="Please enter your Lastname">
And the fields you validate, you can add a validatorMessage="<Message>"
** UPDATE *
If you want to use Bean Validation, like described in my comment,go this way:
// for example your NamesBean
#Named(value = "namesBean")
#SessionScoped
public class NamesBean {
// attributes
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Size(min=3, max=10, message="Min 3 and max 10 characters")
public String getFirstname() {
return firstName;
}
}
and the xhtml
<h:message for="lastName"/>
<h:inputText id="lastName" value="#{account.lastName}" required="true" requiredMessage="Please enter your Lastname">
Thats it.
I managed it this way (personnaly) :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<ui:composition template="/WEB-INF/templates/basic.xhtml">
<ui:define name="content">
<h:form>
<h:panelGrid columns="3">
<h:outputText value="Firstname"/>
<h:inputText id="firstName" value="#{account.firstName}" required="true" requiredMessage="The field is empty" validatorMessage="String is not valid (only characters a-z A-Z)">
<f:validateRegex pattern="[a-zA-Z]+"/>
</h:inputText>
<h:message for="firstName" errorStyle="color:red; display:block"/>
<h:outputText value="Lastname"/>
<h:inputText id="lastName" value="#{account.lastName}" required="true" requiredMessage="The field is empty" validatorMessage="String is not valid (only characters a-z A-Z)">
<f:validateRegex pattern="[a-zA-Z]+"/>
</h:inputText>
<h:message for="lastName" errorStyle="color:red; display:block"/>
<h:outputText value="Login"/>
<h:inputText id="login" value="#{account.login}" required="true" requiredMessage="The field is empty" validatorMessage="String is not valid (only characters a-z A-Z 0-9)">
<f:validateRegex pattern="[a-zA-Z0-9]+"/>
</h:inputText>
<h:message for="login" errorStyle="color:red; display:block"/>
<h:outputText value="Password"/>
<h:inputSecret id="password1" value="#{account.password1}" required="true" requiredMessage="Enter a password">
</h:inputSecret>
<h:message for="password1" errorStyle="color:red; display:block"/>
<h:outputText value=""/>
<h:inputSecret id="password2" value="#{account.password2}"/>
<h:outputText value=""/>
<h:outputText value="Address"/>
<h:inputText id="address" value="#{account.address}" required="true" requiredMessage="The field is empty" validatorMessage="Wrong address (eg.: 42bis My address)">
<f:validateRegex pattern="[a-zA-Z0-9]+ [a-zA-Z ]+"/>
</h:inputText>
<h:message for="address" errorStyle="color:red; display:block"/>
<h:outputText value="Email"/>
<h:inputText id="email" value="#{account.email}" required="true" requiredMessage="The field is empty" validatorMessage="The email is not valid">
<f:validateRegex pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$"/>
</h:inputText>
<h:message for="email" errorStyle="color:red; display:block"/>
</h:panelGrid>
<h:commandButton value="Register" action="#{account.action}"/>
<h:messages globalOnly="true"/>
</h:form>
</ui:define>
</ui:composition>
</html>

gmap PrimeFaces p:ajax

I am trying to update the google map of PrimeFaces with the new latitude, longitude with the help of p:ajax, but it is not working...I'm using JSF 2.0. I have used p:ajax earlier in the similar way and it worked beautifully. Any idea why this does not work? The following is the code, contForm is the id of the form.
<h:outputText value="Latitude :"/>
<h:inputText value="#{confirmBrandRegistration.newBrand.mapLatitude}" size="10">
<p:ajax event="blur" update="contForm:gMapID"/>
</h:inputText>
<h:outputText value=" Longitude :"/>
<h:inputText value="#{confirmBrandRegistration.newBrand.mapLongitude}" size="10" >
<p:ajax event="blur" update="contForm:gMapID"/>
</h:inputText>
<h:outputText value=" Marker :"/>
<h:inputText value="#{confirmBrandRegistration.newBrand.mapMarker}" size="20" >
<p:ajax event="blur" update="contForm:gMapID"
listener="#{confirmBrandRegistration.updateMarker}"/>
</h:inputText>
</h:panelGrid>
<p:outputPanel id="gMapID">
<f:view contentType="text/html">
<p:gmap center="#{confirmBrandRegistration.newBrand.mapLatitude}, #{confirmBrandRegistration.newBrand.mapLongitude}"
zoom="16" type="HYBRID" streetView="true"
model="#{confirmBrandRegistration.simpleModel}"
style="width:500px;height:400px" />
</f:view>
</p:outputPanel>
I solved it right now:)
index page:
<h:panelGroup id="pmap">
<p:inputText value="#{mapManager.address}" label="Adresa" />
<h:outputText value="#{mapManager.geo}" id="m" />
<p:commandButton value="OK" actionListener="#{mapManager.updateMapCenter(ae)}" update="pmap" />
<p:gmap center="#{mapManager.geo}"
zoom="7"
type="HYBRID"
style="width:800px;height:400px"
streetView="true"
model="#{mapManager.map}"
overlaySelectListener="#{mapBean.onMarkerSelect}"
>
<p:gmapInfoWindow>
<p:outputPanel style="text-align:center; display:block; margin:auto:">
<h:outputText value="#{mapManager.marker.title}" />
wserw
</p:outputPanel>
</p:gmapInfoWindow>
</p:gmap>
</h:panelGroup>
part of managed bean:
private MapModel map;
private Marker marker;
private String address;
private String geo="49.817491999999992, 15.4729620";
public MapManager() {
}
#PostConstruct
public void init() {
events = edao.findAll();
map = new DefaultMapModel();
for (Event event : events) {
Marker m=new Marker(new LatLng(event.getLat(), event.getLng()), event.getName());
map.addOverlay(m);
}
}
public void updateMapCenter(ActionEvent ae) {
GMapService gs=new GMapService();
LatLng geo=gs.getGeocode(address);
this.geo=geo.getLat()+","+geo.getLng();
}
hope it solved your problem.

Resources