JSP <f:validator> didn't see my validation class - java

........ ............ ........... ............ ................
My application doesn't display the validated data and I didn't know why.
In other cases it works but not this time, and I really didn't know what's the matter.
JSP:
(...)
<div id="contentarea">
<c:if test="${userBean.isOnline}">
<h2>
<h:outputLabel value="#{msg.vehicleRegistration}" />
</h2>
<fieldset>
<h:form>
<h:outputLabel value="#{msg.brandLabel}" />
<h:inputText id="brand" value="#{carBean.brand}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<h:message for="brand" style="color:red" />
<br />
<h:outputLabel value="#{msg.surnameLabel}" />
<h:inputText id="surname" value="#{carBean.surname}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<h:message for="surname" style="color:red" />
<br />
<h:outputLabel value="#{msg.addresLabel}" />
<h:inputText id="address" value="#{carBean.adress}">
<f:validator validatorId="TextValidator" />
</h:inputText>
<br />
<h:message for="address" style="color:red" />
<br />
<h:outputLabel value="#{msg.yearLabel}" />
<h:inputText id="year" value="#{carBean.year}">
<f:validator validatorId="NumberValidator" />
</h:inputText>
<h:message for="year" style="color:red" />
<br />
<br />
<h:commandButton value="#{msg.addButtonLabel}" onclick="alert('#{msg.vehicleAdded}')"
action="#{carList.addToList(carBean)}" styleClass="myButton" />
</h:form>
</fieldset>
</c:if>
<c:if test="${!userBean.isOnline}">
<h2>
<h:outputLabel value="#{msg.accessDenied}" />
</h2>
<b><a href="/Project"> <h:outputText
value="#{msg.accessDeniedLabel}" />
</a> </b>
</c:if>
</div>
(...)
</html>
TextValidator.java
package my.jsf.code;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
public class TextValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
FacesContext facesContext = FacesContext.getCurrentInstance();
String localePL = facesContext.getViewRoot().getLocale()
.toLanguageTag();
String text = localePL.equals("pl") ? "Pole nie może być puste!"
: "Field cannot be empty!";
String val = (String) value;
if (val == null) {
FacesMessage msg = new FacesMessage(text);
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
}
}

Related

Can't get submit button work

I am new to java and trying to learn how to add data into database.
I cannot make my submit button work. I am getting error of "target unreachable". I am using hibernate and phpMyAdmin.
As I said I new to this. Please let me know if I am missing information that needed.
Instead of calling class in my submit button should I create private String method for the text boxes?
I am confused.
Thanks a lot for your help.
additem.xhtml
<h:body>
<ui:composition template="template.xhtml">
<ui:define name="content">
<h1>Add a New Item</h1>
<br />
<h:form>
<p:panel id="panel" header="Enter an Item" style="margin-bottom:20px;">
<p:growl id="growl" showDetail="true" sticky="false" />
<h:outputLabel value="Item Number" />Item Number:
<p:inputText value="#{LibraryItem.itemNumber}" />
<br />
<h:outputLabel value="Title" />Title:
<p:inputText value="#{LibraryItem.title}" />
<br />
<h:outputLabel for="type" value="Type">Item Type:
<p:selectOneMenu value="#{libraryItem.type}" style="width:228px">
<f:selectItem itemValue="" itemLabel="Select One" />
<f:selectItem itemValue="book" itemLabel="Book" />
<f:selectItem itemValue="magazine" itemLabel="Magazine" />
<f:selectItem itemValue="movie" itemLabel="Movie" />
<f:selectItem itemValue="music" itemLabel="Music" />
</p:selectOneMenu>
</h:outputLabel>
<br />
<h:outputLabel value="Status" />Status:
<p:inputText value="#{LibraryItem.status}" />
<br />
<p:commandButton value="Submit" actionListener="#{AddLibraryItem.addItem}" update="growl" />
<br />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
AddLibraryItem.java
#Named
#ManagedBean
#Scope("request")
public class AddLibraryItem {
//no arg constructor
public AddLibraryItem(){
}
#Inject private LibraryItem libraryItem;
#Inject private ILibraryService libraryService;
public String addItem(){
//return value
String returnValue = "success";
//assign values
libraryItem.setStatus("CHECKED_IN");
//add to library
try {
libraryService.add(libraryItem);
displayMessage("Success","Item added");
}catch (Exception e){
displayMessage("Error", e.toString());
return "fail";
}
return returnValue;
}
//Getters and Setters
public LibraryItem getLibraryItem() {
return libraryItem;
}
public void setLibraryItem(LibraryItem libraryItem) {
this.libraryItem = libraryItem;
}
public ILibraryService getLibraryService() {
return libraryService;
}
public void setLibraryService(ILibraryService libraryService) {
this.libraryService = libraryService;
}
//method to display messages
private void displayMessage(String title, String message){
//get faces context
FacesContext currentInstance = FacesContext.getCurrentInstance();
//message to show
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, title, message);
//display the message
currentInstance.addMessage(null, fm);
}
}

jsf Button reacts after second click

I have a huge problem with my jsf page. I have to pass a Parameter in Post request to a request scoped Bean. All works fine except one little bug. The button to update my information reacts only from second click on.
This Page has to be request scope.
Everytime i push the button it first runs the #PostConstruct and is then ready for a click. I tried to delete the PostConstruct method but my program than stops. I tried nearly everything. Any ideas please?
Here is my Code: I enter this page by calling the Methode "showEditEvent" from another Bean.
package model.backingBean.event;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
//import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import model.backingBean.system.SessionBean;
import model.bean.event.Event;
import model.database.EventManager;
import model.enums.EColorTheme;
import model.exceptions.DatabaseException;
import model.utility.Cryptography;
import model.utility.system.ConfigurationReader;
/**
* Bean for is responsible for the edit actions, which are performed with an
* event. That means you can change eventdetails.
*
* #author 101 Computing
*
*/
#ManagedBean
#RequestScoped
public class EditEventBean implements Serializable {
private static final long serialVersionUID = 1L;
private Event event;
private UIComponent generateVerCode;
private UIComponent updateButton;
private Part uploadedImage;
private static Logger logger = LogManager.getLogger(EditEventBean.class
.getName());
private String color;
private ResourceBundle rb = FacesContext.getCurrentInstance().getApplication().
getResourceBundle(FacesContext.getCurrentInstance(),"msgs");
#ManagedProperty("#{param.eventID}")
private int eventID;
/**
* Injects SessionBean.
*/
#ManagedProperty("#{sessionBean}")
private SessionBean sb;
public String showEditEvent(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
this.setEventID(eventID);
try {
this.event = EventManager.getEvent(eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exceptions_database"), null);
fcxt.addMessage(null, msgs);
}
return "/facelets/eventAdmin/editEvent.xhtml";
}
public int getEventID() {
return eventID;
}
public void setEventID(int eventID) {
this.eventID = eventID;
}
/**
* Method initializes the event.
*
* #throws IOException
*/
#PostConstruct
public void init() {
FacesContext fcxt = FacesContext.getCurrentInstance();
String id = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("eventID");
if (id != null) {
this.eventID = Integer.parseInt(id);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
}
}
/**
*
* #param eventID
* #return
*/
public void update(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
if (this.event.getEndOfEvent().after(this.event.getStartOfEvent())
&& this.event.getEntireTicketamount() > 0) {
if (this.uploadedImage != null) {
upload();
}
if (this.color.equals(EColorTheme.THEME_PINK.toString())) {
this.event.setColorTheme(EColorTheme.THEME_PINK);
} else if (this.color.equals(EColorTheme.THEME_BLUE.toString())) {
this.event.setColorTheme(EColorTheme.THEME_BLUE);
}
EventManager.updateEvent(this.event);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
// Message for updating
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_INFO,
rb.getString("editEvent_successUpdate"), null);
fcxt.addMessage(null, msgs);
} else {
// Message for updating
FacesMessage message = new FacesMessage("Not updated "
+ "- ends before it starts!");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(updateButton.getClientId(context), message);
}
}
/**
* Method generates a new verification code and saves it in the database.
*/
public void generateNewVerificationCode(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
String newCode = verificationGenerator();
this.event.setVerificationCode(newCode);
try {
EventManager.setNewVerificationCode(this.event.getEventID(),
newCode);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
FacesMessage message = new FacesMessage("New VC generated.");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(generateVerCode.getClientId(context), message);
logger.info("Generated a new verification code for event with id="
+ this.event.getEventID() + ".");
}
And here is my Facelet
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<ui:composition template="../../templates/basicTemplate.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="eventID" value="#{editEventBean.eventID}" />
<f:viewAction action="#{editEventBean.init}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h1 style="color: #808080; font-size: large">#{msgs.event_editEvent_h1}
</h1>
<br />
<h:form enctype="multipart/form-data">
<f:view>
<input type="hidden" name="eventID"
value="#{editEventBean.eventID}" />
<h:outputText value="#{msgs.editEvent_pictureSize}" /> <br/>
<h:panelGrid columns="3">
<h:outputLabel for="eventPic" value="#{msgs.event_picture}" />
<h:inputFile id="eventPic" value="#{editEventBean.uploadedImage}" sizeLimit="20480"/>
<h:message for="eventPic" errorStyle="color:red" />
<h:outputLabel for="title" value="#{msgs.event_title}" />
<h:inputText id="title" value="#{editEventBean.event.title}"
required="true" requiredMessage="#{msgs.event_reqTitle}"
label="#{msgs.event_title}" size="74">
<f:validateLength minimum="2" maximum="70" />
</h:inputText>
<h:message for="title" errorStyle="color:red" />
<h:outputLabel for="description" value="#{msgs.event_description}" />
<h:inputTextarea id="description"
value="#{editEventBean.event.description}" required="true"
requiredMessage="#{msgs.event_reqDescription}"
label="#{msgs.event_description}" cols="60">
<f:validateLength minimum="2" maximum="500" />
</h:inputTextarea>
<h:message for="description" errorStyle="color:red" />
<h:outputLabel for="location" value="#{msgs.event_location}" />
<h:inputText id="location" value="#{editEventBean.event.location}"
required="true" requiredMessage="#{msgs.event_reqLocation}"
label="#{msgs.event_location}" size="50">
<f:validateLength minimum="2" maximum="50" />
</h:inputText>
<h:message for="location" errorStyle="color:red" />
<h:outputLabel for="startOfEvent"
value="#{msgs.event_editStartDate}" />
<h:inputText id="startOfEvent"
value="#{editEventBean.event.startOfEvent}" required="true"
requiredMessage="#{msgs.event_reqStartDate}"
label="#{msgs.event_startDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="startOfEvent" errorClass="error" />
<h:outputLabel for="endOfEvent" value="#{msgs.event_editEndDate}" />
<h:inputText id="endOfEvent"
value="#{editEventBean.event.endOfEvent}" required="true"
requiredMessage="#{msgs.event_reqEndDate}"
label="#{msgs.event_endDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="endOfEvent" errorClass="error" />
<h:outputLabel for="ticketAmount"
value="#{msgs.event_ticketAmount}" />
<h:inputText id="ticketAmount"
value="#{editEventBean.event.entireTicketamount}" required="true"
requiredMessage="#{msgs.event_reqTicketAmount}"
label="#{msgs.event_ticketAmount}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="ticketAmount" errorStyle="color:red" />
<h:outputLabel for="ticketPrice" value="#{msgs.event_ticketPrice}" />
<h:inputText id="ticketPrice"
value="#{editEventBean.event.ticketPrice}" required="true"
requiredMessage="#{msgs.event_reqTicketPrice}"
label="#{msgs.event_ticketPrice}" size="50">
<f:convertNumber type="currency" currencySymbol="€"
maxFractionDigits="2" />
</h:inputText>
<h:message for="ticketPrice" errorStyle="color:red" />
<h:outputLabel for="accountNumber"
value="#{msgs.event_accountNumber}" />
<h:inputText id="accountNumber"
value="#{editEventBean.event.accountNumber}" required="true"
requiredMessage="#{msgs.event_reqAccountNumber}"
label="#{msgs.event_accountNumber}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="accountNumber" errorStyle="color:red" />
<h:outputLabel for="cashPayment" value="#{msgs.event_cashPayment}" />
<h:selectBooleanCheckbox id="cashPayment"
value="#{editEventBean.event.cashPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="creditPayment"
value="#{msgs.event_creditPayment}" />
<h:selectBooleanCheckbox id="creditPayment"
value="#{editEventBean.event.creditPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive" value="#{msgs.event_isActive}" />
<h:selectBooleanCheckbox id="isActive"
value="#{editEventBean.event.isActive}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive"
value="#{msgs.event_chooseTicketColor}" />
<h:selectOneMenu value="#{editEventBean.color}">
<f:selectItem itemValue="PINK" itemLabel="Pink" />
<f:selectItem itemValue="BLUE" itemLabel="Blue" />
</h:selectOneMenu>
<h:outputLabel></h:outputLabel>
<h:commandButton id="updateButton" value="#{msgs.event_update}"
action="#{editEventBean.update(editEventBean.eventID)}"
binding="#{editEventBean.updateButton}" />
<h:message for="updateButton" infoClass="info" />
</h:panelGrid>
<h:panelGrid columns="4">
<h:outputLabel for="verificationCode" value="#{msgs.event_vc}" />
<h:inputText id="verificationCode"
value="#{editEventBean.event.verificationCode}" readonly="true">
</h:inputText>
<h:commandButton id="generateVerCode"
value="#{msgs.event_generateVC}"
action="#{editEventBean.generateNewVerificationCode(editEventBean.eventID)}"
binding="#{editEventBean.generateVerCode}" />
<h:message for="generateVerCode"
infoStyle="color:darkgreen; font-weight: bold;" />
</h:panelGrid>
</f:view>
</h:form>
<br />
</ui:define>
</ui:composition>
Found my error. And it was as easy as frustrating…
the
h:form enctype="multipart/form-data"
needs an id. I need the enctype for uploading files. And then the form has to have an id…
Two pages helped me finding this bug:
"7. If a parent of the with the UICommand button is been rendered/updated by an ajax request beforehand, then the first action will always fail."
(commandButton/commandLink/ajax action/listener method not invoked or input value not updated)
and this example of using file upload:
http://jsflive.wordpress.com/2013/04/23/jsf22-file-upload/
It's difficult find such tiny errors if the code is not your own…

Forward variable on the next page

I have a Users table. Added, view and delete work. But I have problem to edit.
My list page:
<h:form id="form">
<p:dataTable styleClass="table" value="#{userMB.allAdmins}" var="admin" paginator="true" rows="15" rowKey="#{admin.id}" selection="#{userMB.user}" selectionMode="single">
<f:facet name="header">
Lista administratorów
</f:facet>
<p:column headerText="#{msg.firstName}">
<h:outputText value="#{admin.firstName}" />
</p:column>
<p:column headerText="#{msg.lastName}">
<h:outputText value="#{admin.lastName}" />
</p:column>
<p:column headerText="#{msg.personalId}">
<h:outputText value="#{admin.personalId}" />
</p:column>
<f:facet name="footer">
<p:commandButton id="viewButton" value="#{msg.info}" icon="ui-icon-search"
update=":form:display" oncomplete="userDialog.show()"/>
<p:commandButton action="#{userMB.createStart()}" value="#{msg.add}" icon="ui-icon-plus" />
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}" >
<f:setPropertyActionListener target="#{userMB.user}" value="#{userMB.user}" />
</p:commandButton>
<p:commandButton action="#{userMB.deleteUser()}" value="#{msg.delete}" icon="ui-icon-close"/>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Administrator" widgetVar="userDialog" resizable="false"
width="300" showEffect="clip" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<f:facet name="header">
<p:graphicImage value="./../../images/person4.png" width="150" height="150"/>
</f:facet>
<h:outputText value="#{msg.firstName}" />
<h:outputText value="#{userMB.user.firstName}" />
<h:outputText value="#{msg.lastName}" />
<h:outputText value="#{userMB.user.lastName}" />
<h:outputText value="#{msg.personalId}" />
<h:outputText value="#{userMB.user.personalId}" />
</h:panelGrid>
</p:dialog>
</h:form>
I want to send the selected user on the next page:
I use aciontListener:
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}" >
<f:setPropertyActionListener target="#{userMB.user}" value="#{userMB.user}" />
</p:commandButton>
My edit page where I want to send user:
<h:form>
<div id="userPanel">
<h:inputHidden value="#{userMB.user}" />
<p:panel id="panelUser" header="Edytuj administratora" >
<div id="panelImage">
<img src="./../../images/person4.png" alt="person" width="150px" height="130px"/>
</div>
<h:panelGrid columns="3">
<p:outputLabel for="firstName" value="#{msg.firstName}"></p:outputLabel>
<p:inputText id="firstName" value="#{userMB.user.firstName}" label="#{msg.firstName}" required="true">
<f:validator validatorId="nameValidator" />
<p:ajax update="msgFristName" event="keyup" />
</p:inputText>
<p:message for="firstName" id="msgFristName"/>
<p:outputLabel for="lastName" value="#{msg.lastName}"></p:outputLabel>
<p:inputText id="lastName" value="#{userMB.user.lastName}" label="#{msg.lastName}" required="true">
<f:validator validatorId="nameValidator" />
<p:ajax update="msgLastName" event="keyup" />
</p:inputText>
<p:message for="lastName" id="msgLastName"/>
<p:outputLabel for="personalId" value="#{msg.personalId}"></p:outputLabel>
<p:inputText id="personalId" value="#{userMB.user.personalId}" label="#{msg.personalId}" required="true">
<f:validator validatorId="personalIdValidator" />
<p:ajax update="msgPersonalId" event="keyup" />
</p:inputText>
<p:message for="personalId" id="msgPersonalId"/>
<p:outputLabel for="password" value="#{msg.password}"></p:outputLabel>
</p:panel>
</div>
</h:form>
I added: <h:inputHidden value="#{userMB.user}" /> but I do not see data user, only empty field. How do I send this person? I used once this method in other project, a little different without primefaces and it worked. Why now does not work?
Method editStart:
public String editStart() {
return "editStart";
}
faces-config:
<navigation-case>
<from-outcome>editStart</from-outcome>
<to-view-id>/protected/admin/adminEdit.xhtml</to-view-id>
<redirect/>
</navigation-case>
When I'm on the side adminEdit I edited the pool and do editUser method:
public String editUser() {
FacesContext context = FacesContext.getCurrentInstance();
Map requestParameterMap = (Map) context.getExternalContext().getRequestParameterMap();
try {
String userRole = requestParameterMap.get("userRole").toString();
String active = requestParameterMap.get("active").toString();
Boolean act = Boolean.parseBoolean(active);
user.setRole(userRole);
user.setActive(act);
userDao.update(user);
} catch (EJBException e) {
sendErrorMessageToUser("Edit error");
return null;
}
sendInfoMessageToUser("Account edited");
return user.getRole() + "List";
}
My method editStart use only for navigation.
You can either consider Przemek's answer or use one of the 4 ways of passing a parameter to a backing bean.
1. Method expression
2. f:param
3. f:atribute
4. f:setPropertyActionListener
For very well explained full explanation refer to this
It has easy to understand examples. Take a look and pick what fits your needs.
Or simply:
In the actual managed bean...
public String navigationButtonListener(User parameter) {
FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
.put("parameterAttribute", parameter);
return "my-destination-page";
}
In the destination managed bean...
#PostConstruct
public void init(){
myAttribute= (User) FacesContext.getCurrentInstance()
.getExternalContext().getRequestMap().get("parameterAttribute");
}
Good Luck!
You can pass your userid through the session.
Add a parameter to your commandLink
<p:commandButton action="#{userMB.editStart()}" value="#{msg.edit}>
<f:param name="userId" value="#{userMB.user.id}" />
</p:commandButton>
In your backing bean do this
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest myRequest = (HttpServletRequest)context.getExternalContext().getRequest();
HttpSession mySession = myRequest.getSession();
Integer userId = Integer.parseInt(myRequest.getParameter("userId"));
After that you can reload the user you want to edit with the Id you got

p:commandButton not working in p:wizard

The problem that I am facing is that <p:commandButton> with id="emailav" doesn't call the action method emailAvailability. I am using it inside p:wizard and also I have included the following block of code inside h:form.
1) xhtml
<p:tab id="personal" title="Personal">
<p:panel header="Personal Details" style="font-size:small">
<h:panelGrid columns="3" columnClasses="label, value"
styleClass="grid">
<h:outputText value="Username*" />
<p:inputText id="usrname" required="true" label="Username"
value="#{registrationBean.user.userName}"
requiredMessage="Username required" />
<p:message for="usrname"></p:message>
<h:outputText value="Firstname: *" />
<p:inputText id="frstname" required="true" label="Firstname"
value="#{registrationBean.user.firstName}"
requiredMessage="Firstname required" />
<p:message for="frstname"></p:message>
<h:outputText value="Lastname: *" />
<p:inputText id="lstname" required="true" label="Lastname"
value="#{registrationBean.user.lastName}"
requiredMessage="Lastname required" />
<p:message for="lstname"></p:message>
<h:outputText value="Password: *" />
<p:password id="pwd1" value="#{registrationBean.user.password}"
feedback="true" match="pwd2" label="Password" required="true"
requiredMessage="Password required" />
<p:message for="pwd1"></p:message>
<h:outputText value="Confirm Password: *" />
<p:password id="pwd2" value="#{registrationBean.user.password}"
label="Confirm Password" required="true"
requiredMessage="Enter the password again" />
<p:message for="pwd2"></p:message>
<h:outputText value="Date of Birth(dd/MM/yyyy):" />
<p:inputText id="dob" label="Date of Birth"
value="#{registrationBean.user.birthDate}" />
<p:message for="dob"></p:message>
<h:outputText value="Gender: " />
<p:selectOneMenu id="gender" value="#{registrationBean.user.gender}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Male" itemValue="Male" />
<f:selectItem itemLabel="Female" itemValue="Female" />
<f:selectItem itemLabel="Other" itemValue="Other" />
</p:selectOneMenu>
<p:message for="gender"></p:message>
<h:outputText value="Relationship Status: " />
<p:selectOneMenu id="relationship"
value="#{registrationBean.user.relationship}">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItem itemLabel="Single" itemValue="Single" />
<f:selectItem itemLabel="Committed" itemValue="Committed" />
<f:selectItem itemLabel="Open relationship" itemValue="Open relationship" />
<f:selectItem itemLabel="Its comlicated" itemValue="Its complicated" />
</p:selectOneMenu>
<p:message for="relationship"></p:message>
<h:outputText value="Email: *" />
<p:inputText id="email" label="Email"
value="#{registrationBean.user.email}" required="true"
requiredMessage="Email required"/>
<p:message for="email"/>
<p:commandButton id="emailav" value="email availability"
action="#{registrationBean.emailAvailability}" update="emailav" />
<p:message for="emailav"></p:message>
<p:commandButton style="display:none"/>
<h:outputText value="Skip to last: " />
<h:selectBooleanCheckbox value="#{registrationBean.skip}" />
</h:panelGrid>
</p:panel>
</p:tab>
2)Backing bean
public String emailAvailability() {
logger.info("inside emailAvailability");
FacesContext context = FacesContext.getCurrentInstance();
Query query = em.createQuery("SELECT u FROM User u", User.class);
List<User> results = query.getResultList();
Iterator<User> it = results.listIterator();
while (it.hasNext()) {
if (it.next().getEmail().equals(user.getEmail())) {
context.addMessage(null,
new FacesMessage("Email already taken"));
}
}
context.addMessage(null, new FacesMessage("Email not taken"));
return "success";
}
try adding process="#this"
like
<p:commandButton
value="Add Site 1"
update="editor"
title="Remover"
action="#{jobEngine2MB.addSiteType1}"
process="#this" />

How do I get "p:focus" to work properly in this simple app (its currently not "focusing" at all)

PROBLEM:
The PrimeFaces "p:focus" tag is not focusing.
-I.e., when the xhtml page is presented to the user, no input fields are in focus.
QUESTION:
Why not? How can I get "p:focus" to work properly in this simple app?
(NOTE: using Java 6, Mojarra v2.1.11, PrimeFaces v3.4.2)
index.jsp
<?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">
<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"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
<title>testcal2 - index.xhtml</title>
<meta charset="utf-8" />
</h:head>
<h:body>
<h:form id="queryForm">
<f:event type="postValidate" listener="#{testBean.validate}" />
<h:panelGroup id="msgsx">
<p:messages showSummary="true"/>
</h:panelGroup>
<p:panel id="queryPanel" header="Test p:focus..." style="width:100%;">
<p:focus context="queryPanel"/>
<h:panelGroup id="msgs" style="height:1.5em; text-align: center;display:block">
<p:message id="lastName_msg" for="lastName" style="display:none;" showSummary="false"/>
<p:message id="birthDate_msg" for="birthDate" style="display:none;" showSummary="false"/>
<p:message id="startDate_msg" for="startDate" style="display:none;" showSummary="false"/>
</h:panelGroup>
<h:panelGroup id="querypanelgroup" style="display:inline-block;">
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Last Name:" for="lastName"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="lastName"
value="#{testBean.parmMap['lastName']}"
requiredMessage="last name required"
size="95"
maxlength="95"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Birth Date:" for="birthDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="birthDate"
value="#{testBean.parmMap['birthDate']}"
requiredMessage="birth date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(1).show();$(this).mask('99/99/9999');return false;">
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<h:panelGroup>
<h:panelGroup style="text-align:right;vertical-align:middle;display:inline-block;width:150px">
<p:outputLabel style="margin-right: 5px;" value="Start Date:" for="startDate"/>
</h:panelGroup>
<h:panelGroup style="margin-left: 4px; vertical-align:middle;display:inline-block;width:250px;">
<p:inputText
id="startDate"
value="#{testBean.parmMap['startDate']}"
requiredMessage="start date required"
converter="dpConverter"
styleClass="datePicker"
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(2).show();$(this).mask('99/99/9999');return false;">
<!-- optional to populate another field with same value...
onchange="$('...hashSymbolHere...queryForm\\:endDate').val($(this).val());">
-->
<p:ajax event="change" process="#this" update="#this"/>
</p:inputText>
</h:panelGroup>
</h:panelGroup>
<br/>
<br/>
<p:commandButton
id="submit"
value="Submit"
oncomplete="applyDatePicker();"
type="submit"
update="#form"
process="#form"
action="#{testBean.submitQuery}"
style="width:150px;"
styleClass="button"/>
<p:commandButton
value="Reset"
update="#form"
onclick="location.reload();return true;"
process="#this"
actionListener="#{testBean.reset}"
immediate="true"
ajax="false"/>
</h:panelGroup>
</p:panel>
</h:form>
<h:outputStylesheet library="styles" name="query.css" />
<h:outputScript library="primefaces" name="/jquery/jquery.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/ui/jquery-ui.custom.js" />
<h:outputScript library="primefaces" name="/jquery/plugins/inputmask/maskedinput.js" />
<h:outputScript library="js" name="index.js" target="head" />
</h:body>
</f:view>
</html>
index.js
$(document).ready(function()
{
applyDatePicker();
});
function applyDatePicker(){
$('.datePicker').datepicker(
{
showOn: 'button',
buttonText: "Choose",
showButtonPanel: true,
showOptions: {direction: 'up'},
changeYear: true,
changeMonth: true,
yearRange: "c-120:c+0"
});
}
TestBean.java
package aaa.bbb.ccc.war;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component("testBean")
#Scope("request")
public class TestBean implements Serializable
{
public TestBean()
{
parmMap = this.getParmMap();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
public void reset(ActionEvent event)
{
LinkedHashMap<String, Object> m = new LinkedHashMap<String, Object>();
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("parmMap");
setParmMap(m);
}
public String submitQuery()
{
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("hitlistData");
if (this.getParmMap().isEmpty())
{
return "";
}
return "/page2.xhtml?faces-redirect=true";
}
private static LinkedHashMap<String, Object> parmMap;
public LinkedHashMap<String, Object> getParmMap()
{
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("parmMap");
if (null == map)
{
map = new LinkedHashMap<String, Object>();
}
return map;
}
public void setParmMap(LinkedHashMap<String, Object> map)
{
parmMap = map;
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("parmMap", parmMap);
}
private static SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
public void validate(ComponentSystemEvent e) throws ParseException
{
LinkedHashMap parmMap = this.getParmMap();
UIForm queryForm = (UIForm) e.getComponent();
FacesContext fc = FacesContext.getCurrentInstance();
UIInput lastName_c = (UIInput) queryForm.findComponent("lastName");
String lastName = (String) (lastName_c.getValue());
UIInput birthDate_c = (UIInput) queryForm.findComponent("birthDate");
String birthDate = (String) birthDate_c.getValue();
UIInput startDate_c = (UIInput) queryForm.findComponent("startDate");
String startDate = (String) startDate_c.getValue();
try
{
if (null != lastName && lastName.trim().length() > 0)
{
if (null == birthDate || birthDate.length() < 1)
{
birthDate_c.setValid(false);
fc.addMessage(birthDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, birthDate_c.getRequiredMessage(), birthDate_c.getRequiredMessage()));
}
else
{
birthDate_c.setValid(true);
}
}
else
{
birthDate_c.setValid(true);
}
if (null == startDate || startDate.trim().length() < 1)
{
startDate_c.setValid(false);
fc.addMessage(startDate_c.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, startDate_c.getRequiredMessage(), startDate_c.getRequiredMessage()));
}
else
{
startDate_c.setValid(true);
}
if (fc.getMessageList().size() > 0)
{
fc.renderResponse();
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
}
}
It's because you're returning false on focus here:
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();return false;" >
</p:inputText>
Returning false causes the event's default behaviour to be blocked.
To fix your problem, simply remove return false; from onfocus attribute of the input component.
<p:inputText
...
onfocus="$('#queryForm\\:msgs > div').hide();$('#queryForm\\:msgs > div').eq(0).show();" >
</p:inputText>

Categories

Resources