JSF Validator Problems - jsf

I'm doing the following:
I want do the validation implements interface validator of JSF. I have the following code:
index.xhtml:
<h:form id="inicio">
<p:panel id="panel" header="Digite sus Credenciales">
<p:focus context="panel"/>
<h:panelGrid id="gridInicio" columns="3" cellpadding="5" >
<p:outputLabel for="identificacion" value="Identificacion:"/>
<p:inputText id="identificacion" onfocus="true" value="#
{ingresoMB.usuario.identificacionUsuario}"
required="true"
label="Identificacion">
<f:validator validatorId="numericoValidator"/>
<f:validateLength minimum="2" />
</p:inputText>
</h:panelGrid>
<p:commandButton value="Ingresar" update="panel"
actionListener="#{ingresoMB.verificarInicio()}"
icon="ui-icon-check" />
</p:panel>
face-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
<validator>
<validator-id>numericoValidator</validator-id>
<validator-class>co.com.patios.mb.util.validacioncomponentes.numericoValidator</validator-class>
</validator>
</faces-config>
numericoValidator.java:
import javax.faces.validator.ValidatorException;
public class numericoValidator implements Validator {
public numericoValidator() {
// TODO Auto-generated constructor stub
}
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String identificacion = (String) value;
if(!validarNumerico(identificacion)){
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setDetail("Campo debe ser Numerico, Verifique !!!");
message.setSummary("Campo debe ser Numerico, Verifique !!!");
context.addMessage("inicio", message);
throw new ValidatorException(message);
}
}
private boolean validarNumerico(String value){
try{
Long.parseLong(value);
}catch (NumberFormatException e){
return false;
}
return true;
}
}
Now, in my index.xhtml I reference
<f:validator validatorId="numericoValidator"/>
validatorId="numericoValidator" is the Id in my face-config.xml:
<validator>
<validator-id>numericoValidator</validator-id>
<validator-class>co.com.patios.mb.util.validacioncomponentes.numericoValidator</validator-class>
</validator>
And co.com.patios.mb.util.validacioncomponentes.numericoValidator is my class java where I perform the validation.
But, I don't understand. Why do it not run ? It isn't showed message.
could you help me ?

Related

Unable to navigate to directory and view page from return value

I have problem understanding why I'm unable to navigate from registrationFlow to protected directory.
In my app, in index.html I have a button which redirects user to registration form ( which is a flow ). That's the part, where user chooses if he want's to login or register new user. My folder structure is:
Web Pages
index.xhtml
protected calatogue
mainPage.xhtml
registration calatogue
registration.xhtml
addClients.xhtml
<h:form>
<h:commandButton class="formButton" value="Zaloguj" action="/Login?faces-redirect=true"/>
<h:commandButton class="formButton" value="Zarejestruj się" action="registration" immediate="true"/>
</h:form>
I have a registrationFlow.xml file which defines behavior how to redirect from page to page
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<flow-definition id="registration">
<view id="registration">
<vdl-document>/registration/registration.xhtml</vdl-document>
</view>
<flow-return id="Cancel">
<from-outcome>
/index
</from-outcome>
</flow-return>
<flow-return id="saveClient">
<from-outcome>
/protected/mainPage
</from-outcome>
</flow-return>
</flow-definition>
</faces-config>
My registration.xhtml file
<h:body>
<p>
#{ null != facesContext.application.flowHandler.currentFlow}
#{facesContext.application.flowHandler.currentFlow.id}
</p>
<div class="registerContainer">
<div class="formContainer">
<h:form id="registerForm" class="registerForm">
<h:outputText value="Username "/>
<h:inputText id="username" value="#{registration.username}"></h:inputText>
<h:outputText value="Password "/>
<h:inputSecret id="password" value="#{registration.password}"></h:inputSecret>
<h:outputText value="Firstname "/>
<h:inputText id="first" value="#{registration.first}"></h:inputText>
<h:outputText value="Lastname "/>
<h:inputText id="last" value="#{registration.last}"></h:inputText>
<h:outputText value="Email "/>
<h:inputText id="email" value="#{registration.email}"></h:inputText>
<h:commandButton id="register" action="#{registration.register}" value="Zarejestruj" style="margin: 15px auto; width: 35%; "></h:commandButton>
<h:commandButton action="Cancel" value="Anuluj" style="margin: 15px auto; width: 35%; "></h:commandButton>
<h:messages for="register"/>
</h:form>
</div>
</div>
</h:body>
And addClients
<h:body>
<h1>Add clients to registered user</h1>
<p>
#{ null != facesContext.application.flowHandler.currentFlow}
#{facesContext.application.flowHandler.currentFlow.id}
</p>
<h:form id="clientsForm">
<c:forEach items="#{clientManagement.clientsList}" var="client">
<h:outputText value="Client Name"/>
<h:inputText id="clientName" value="#{client.name}"></h:inputText>
<h:outputText value="Client company name" />
<h:inputText id="clientCompany" value="#{client.companyName}"></h:inputText>
<h:outputText value="Website" />
<h:inputText id="clientWebsit" value="#{client.website}"></h:inputText>
<h:outputText value="Client Email"/>
<h:inputText id="clientEmail" value="#{client.clientEmail}"></h:inputText> <br></br><br></br>
</c:forEach>
<h:commandButton value="Add client" action="#{clientManagement.addClients()}" immediate="true">
<f:ajax execute="#form" render="clientsForm" />
</h:commandButton>
<h:commandButton id="saveClients" value="Save clients" action="#{clientManagement.saveClient}">
</h:commandButton><br></br>
<h:messages for="saveClients"/>
</h:form>
</h:body>
And last file - ClientManagement.java file which validates passed emails, creates new form for client and saves list of clients passed from addClients.xhtml to database. This is the place I have no idea why it doesn't work. In method saveClient if everything saved I want to redirect user to path ../protected/mainPage.xhtml but it doesn't work.
#Named
#ViewScoped
public class ClientManagement implements Serializable {
private List<Client> clientsList = new ArrayList<Client>();
private List<String> clientsEmail;
private List<Client> allClients;
private User loggedUser;
#Inject
private ClientFacade clientDAO;
#PostConstruct
public void init() {
HttpSession session = SessionUtil.getSession();
User user = (User) session.getAttribute("user");
loggedUser = user;
System.out.println(loggedUser);
}
public Boolean validateEmail(String email) {
String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\#([\\w]+\\.)+[\\w]+[\\w]$";
return email.matches(regex);
}
public void delete(Client client) {
clientDAO.remove(client);
}
public void addClients() {
clientsList.add(new Client());
}
public String saveClient() {
try {
clientsList.forEach((client) -> {
boolean validateEmail = validateEmail(client.getClientEmail());
if (validateEmail) {
Client newClient = new Client();
newClient.setName(client.getName());
newClient.setCompanyName(client.getCompanyName());
newClient.setWebsite(client.getWebsite());
newClient.setClientEmail(client.getClientEmail());
newClient.setUserid(loggedUser);
try {
clientDAO.add(newClient);
} catch (Exception e) {
throw new Error(e);
}
} else if (validateEmail == false) {
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage("clientsForm:saveClients", new FacesMessage("Provided email is invalid." + client.getClientEmail()));
}
});
} catch (Error e) {
throw new Error(e);
}
FacesContext ctx = FacesContext.getCurrentInstance();
ctx.addMessage( "clientsForm:saveClients", new FacesMessage("Successfully added clients"));
return "mainPage";
}
// getters and setters
}
I have also tried exclude that registrationFlow.xml and in saveClient method return page, but it didn't work as well.
So I've found the answer. I didn't see that my server throw warning in the console
Unable to set request character encoding to UTF-8 from context myApp ... and that was the problem. I'm posting a link as answer if someone encounters the same problem.
answer here

Updating a field after a failed Validation

I am building a web application using the technologies mentioned in the post header. I have searched similar threads, but none of them provided an answer to my problem. I have configured my Maven project, the pom file is correct, JSF and PrimeFaces are working, but I encounter a problem when I do the following:
I copied the Client Side Validation example from the Prime Faces Showcase website, and on my end, it isn't working as expected.
When validation fails for a field, an error appears to the right of the field, and as long as it's there, I cannot update the field. When I try to type something, nothing happens on the screen, but if I highlight the text in the field, I can see it there.
Here's my registration.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<h2>Registration Form</h2>
<h:form id="form">
<p:panel id="panel" header="Form" style="margin-bottom:10px;">
<p:fieldset legend="Registration Form" widgetVar="regWidget" style="width: 600px;">
<h:panelGrid columns="3" width="550" border="0">
<h:outputLabel value="UserName" />
<p:inputText value="#{regCont.prospect.userName}"
id="userName"
required="true"
requiredMessage="UserName is required"
validatorMessage="UserName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="5" maximum="15" for="userName"></f:validateLength>
</p:inputText>
<p:message for="userName"/>
<h:outputLabel value="Password" />
<p:password value="#{regCont.password}"
id="password"
required="true"
requiredMessage="Password is required"
validatorMessage="Password should be of length from 5 to 15 chars"
>
<f:validateRegex pattern="^(?=^.{8,12}$)(?!.*(.)\1{3,})(?=.*[A-Z])(?=.*[a-z]{3,})(?=.*[^a-zA-Z0-9]{2,})(?=.*[0-9]{2,})[a-zA-Z]"/>
</p:password>
<p:message for="password" />
<h:outputLabel value="FirstName" />
<p:inputText value="#{regCont.prospect.firstName}"
id="firstName"
required="true"
requiredMessage="FirstName is required"
validatorMessage="FirstName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="1" maximum="45" for="firstName"></f:validateLength>
</p:inputText>
<p:message for="firstName" display="tooltip" />
<h:outputLabel value="LastName" />
<p:inputText value="#{regCont.prospect.lastName}"
id="lastName"></p:inputText>
<p:message for="lastName" display="tooltip"/>
<h:outputLabel value="Email" />
<p:inputText value="#{regCont.prospect.email}"
id="email"
validatorMessage="Invalid Email">
<f:validateRegex pattern="[a-zA-Z0-9]+#[a-zA-Z]+.[a-zA-Z]{2,3}"></f:validateRegex>
</p:inputText>
<p:message for="email" />
<h:outputLabel value="Nation" />
<p:inputText value="#{regCont.prospect.nation}"
id="nation">
</p:inputText>
<p:message for="nation" />
<h3 style="margin-top:0">User type</h3>
<h:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p:outputLabel for="type" value="User type:" />
<p:selectOneRadio id="type" value="#{regCont.prospect.userType}">
<f:selectItem itemLabel="Delegate" itemValue="Delegate" />
<f:selectItem itemLabel="Leader" itemValue="Leader" />
</p:selectOneRadio>
</h:panelGrid>
<p:commandButton value="Register" update="panel" icon="ui-icon-check" validateClient="true" style="margin-right:10px"/>
<h:commandButton value="Reset p:ajax" style="margin-right:20px;" >
<p:ajax update="panel" resetValues="true" />
</h:commandButton>
</h:panelGrid>
</p:fieldset>
</p:panel>
</h:form>
</h:body>
</html>
And here's my RegistrationController class:
#ManagedBean(name = "regCont")
#RequestScoped
public class RegistrationController implements Controller {
#ManagedProperty(value = "#{prospect}")
private Prospect prospect;
#ManagedProperty(value = "#{user}")
private User user;
private String msg;
private String password;
public void hashPassword() throws NoSuchAlgorithmException {
byte[] salt = Passwords.getNextSalt();
prospect.setSalt(salt);
prospect.setPasswordHash(Passwords.getHashWithSalt(password, salt));
password = "";
}
public Prospect getProspect() {
return prospect;
}
public void setProspect(Prospect prospect) {
this.prospect = prospect;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private void clearAll() {
user.setFirstName("");
user.setLastName("");
user.setNation("");
user.setEmail("");
user.setUserName("");
user.setPasswordHash(null);
prospect.setFirstName("");
prospect.setLastName("");
prospect.setNation("");
prospect.setEmail("");
prospect.setUserType("");
prospect.setUserName("");
prospect.setPasswordHash(null);
}
public void saveUser() {
UserDAO dao = new UserDAO();
dao.createEntity(user);
this.msg = "Member Info Saved Successfull!";
clearAll();
}
public void saveProspect() {
ProspectDAO dao = new ProspectDAO();
try {
hashPassword();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
dao.createEntity(prospect);
this.msg = "Member Info Saved Successfull!";
}
public void reset() {
RequestContext.getCurrentInstance().reset("form");
}
public void updateUser(int id) {
UserDAO dao = new UserDAO();
try {
hashPassword();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
dao.updateEntity(id);
this.msg = "Member Info Update Successfull!";
clearAll();
}
public void deleteUser(int id) {
UserDAO dao = new UserDAO();
dao.deleteEntity(id);
this.msg = "Member Info Delete Successfull!";
clearAll();
}
}
Only case this works is, when I implemented the Reset button, and on a failed validation, I click reset, then I can input values into fields.
Also, when I hover above a field (p:inputText), the cursor doesn't change to the text cursor like on other fields (eg. h:inputText). Really don't have an idea how does the same piece of code work on the PrimeFaces ShowCase web site, and not on my end?
Does anybody have an idea how can I fix this?
I'm using JSF 2.2 + PrimeFaces 5.3

<p:commandButton> doesn't navigate when actionListener=“#{bean.method}” is declared

I am trying to create a page which allows a user to logon to the system and then navigates to the homepage. I have managed to get it to do one or the other but cannot work out how to get it to do both. I have crawled through all the sites and cannot find a suitable answer. Please help. My code is as follows:
XHTML:
<h:form>
<p:growl id="growl" showDetail="true" life="3000" />
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" value="Username: " />
<p:inputText value="#{login.username}" id="username" required="true"
label="username" />
<h:outputLabel for="password" value="Password: " />
<h:inputSecret value="#{login.password}" id="password" required="true"
label="password" />
<p:commandButton ajax="false" id="loginButton" value="Login"
update="growl" actionListener="#{login.login}" />
</h:panelGrid>
</h:form>
Java Class:
#ViewScoped
#ManagedBean
#SessionScoped
public class Login implements Serializable
{
private static final long serialVersionUID = 1L;
private String username;
private String password;
public String login(ActionEvent actionEvent)
{
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg = null;
boolean loggedIn = false;
if(username != null && username.equals("admin") && password != null && password.equals("admin"))
{
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", username);
}
else
{
loggedIn = false;
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Invalid Credentials");
}
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
FacesContext context2 = FacesContext.getCurrentInstance();
context2.getExternalContext().getFlash().setKeepMessages(true);
return "ProEJT?faces-redirect=true";
}
As Requested here is my faces-config.xml:
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-action>#{login.login}</from-action>
<from-outcome>loggedin</from-outcome>
<to-view-id>/ProEJT.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
When I attempted this I altered the return from my login method to "loggedin".
Thanks for any help in advance!!
Action listeners are not supposed to do business logic and navigation. They are supposed to listen on action events. Business logic and navigation should be done in a true action method.
Replace
<p:commandButton ... actionListener="#{login.login}" />
public String login(ActionEvent actionEvent) {}
by
<p:commandButton ... action="#{login.login}" />
public String login() {}
and all should be well.
See also:
Differences between action and actionListener

Primefaces Datatable row selection

Edit2 - I've added the faces-config.xml at the end of the post.
I'm having problems with Primefaces datatable row selection. I want to be able to select a row and move the data into an object that I can then manipulate. I'm using a model based on the primefaces showcase example, but it doesn't work. Frankly, I'm running out of ideas as to what is wrong. Below is my xhtml and managedbean.
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" >
<h:head>
</h:head>
<h:body>
<center>
<h:form id="form">
<p:dataTable id="personTable" var="client" value="#{tableBean.persons}" rowKey="#{client.name}"
selection="#{tableBean.person}" selectionMode="single">
<f:facet name="header">
Click "View" button after selecting a row to see details
</f:facet>
<p:column headerText="Name">
#{client.name}
</p:column>
<p:column headerText="Address">
#{client.address}
</p:column>
<p:column headerText="Phone" >
#{client.phone}
</p:column>
</p:dataTable>
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Name:" />
<h:outputText value="#{tableBean.person.name}" />
<h:outputText value="Address:" />
<h:outputText value="#{tableBean.person.address}" />
<h:outputText value="Phone:" />
<h:outputText value="#{tableBean.person.phone}" />
</h:panelGrid>
</h:form>
</center>
</h:body>
</html>
Managed Bean here:
package com.dave.test;
import java.util.ArrayList;
import java.util.List;
public class TableBean {
private List<Person> persons = null;
private Person person;
public TableBean() {
persons = new ArrayList<Person>();
persons.add(new Person("Jimmy", "18 Maple", "337-278-1019"));
persons.add(new Person("Sally", "47 Oak", "787-509-3819"));
persons.add(new Person("Roger", "754 Fifth Ave.", "926-420-8219"));
persons.add(new Person("Mimi", "891 2nd St.", "713-371-8632"));
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Thanks, Dave
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
facesconfig_2_0.xsd">
<managed-bean>
<managed-bean-name>tableBean</managed-bean-name>
<managed-bean-class>com.dave.test.TableBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
I'm assuming that when you click the row, there is no data. That is because you are using a request scoped bean. This means that when you load the page, the bean is populated. After the page is loaded, the bean is gone.
I would suggest changing your scope to ViewScope to see if that helps at all.
Also, if you're using jsf 2.0, you can use annotations instead of the faces-config.xml file. Your backer would look like this:
package com.dave.test;
import java.util.ArrayList;
import java.util.List;
public class TableBean {
private List<Person> persons = null;
private Person person;
#ManagedBean
#ViewScoped
public TableBean() {
persons = new ArrayList<Person>();
persons.add(new Person("Jimmy", "18 Maple", "337-278-1019"));
persons.add(new Person("Sally", "47 Oak", "787-509-3819"));
persons.add(new Person("Roger", "754 Fifth Ave.", "926-420-8219"));
persons.add(new Person("Mimi", "891 2nd St.", "713-371-8632"));
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Now you can remove your managed bean stuff from faces-config.xml.
EDIT
I just realized you don't have an ajax event to handle the row selection. If you're looking at the primefaces instant row selection, you need to notice that they are using <p:ajax event="rowSelect" ..../> along with a method in the backing bean to handle this.
lo único que debes hacer es al bean TableBean.java quitarle(borrar) el #SessionScoped y a la clase Car.java quitarle #ManagedBean(name = "car") , #SessionScoped , implements Serializable.
esta clase es una simple clase no tiene porque ser un managebean unicamente son datos.
Translated:
All you have to do is to take TableBean.java bean (delete) the #SessionScoped and take Car.java class #ManagedBean (name = "car"), #SessionScoped, implements Serializable. This class is a simple class need not be a managebean only are data.

Open Primefaces dialog and Process Full JSF Lifecycle

I'm doing a <p:commandLink value="#{bundle['registered.home.search.TEXT']}" onclick="webSearchDlg.show();"></p:commandLink> in order to show the below dialog. The p:outputPanel id="searchPnl" always renders after its initially rendered. It never disappears even though the dialogs closeListener="#{dreamSearch.close}" onCloseUpdate="searchTxtPnl,searchPnl" is executed. When I open the dialog after closing it, the panelGrid appears and the <p:inputText id="searchText"> displays the previous value that I tried to clear in the below closeListener method. Any ideas...code below...
<p:dialog header="#{bundle['dreamSearch.HEADER']}"
widgetVar="webSearchDlg" modal="true" styleClass="dialog dialog2"
draggable="false" resizable="false" showEffect="fade"
hideEffect="fade" closeListener="#{dreamSearch.close}" onCloseUpdate="searchTxtPnl,searchPnl">
<div class="dialog-top-reg"></div>
<div class="dialog-middle-reg">
<div class="close-button">
<h:form>
<p:commandButton onclick="webSearchDlg.hide()" />
</h:form>
</div>
<h:form class="dialog-content dialog-content2"
binding="#{dreamSearch.dreamSearchFrm}">
<h1 class="dream-search">
<h:outputText value="#{bundle['dreamSearch.HEADER']}" />
</h1>
<p class="dream-search">
<h:outputText value="#{bundle['dreamSearch.SUBHEADER']}" />
</p>
<div class="dream-search-wrap">
<fieldset>
<p:outputPanel id="searchTxtPnl">
<p:inputText id="searchText" value="#{dreamSearchBean.searchText}"/>
</p:outputPanel>
<p:commandButton styleClass="form-btn1"
value="#{bundle['dreamSearch.search.button.TEXT']}" onclick="webImageSearch()"/>
</fieldset>
</div>
<p:remoteCommand name="webImageSearch" process="searchText, #this" actionListener="#{dreamSearch.search}" update="searchPnl"/>
<p:outputPanel id="searchPnl" styleClass="data-grid-wrap">
<h:outputText value="#{bundle['dreamSearch.imageResults.TEXT']}" rendered="#{dreamSearchBean.shouldRender}"/>
<p:dataGrid var="img" value="#{dreamSearchBean.images}" columns="5"
rows="10" paginator="true" effect="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,15,20" paginatorPosition="bottom" rendered="#{dreamSearchBean.shouldRender}">
<p:column>
<h:panelGrid columns="1" style="width:100%">
<p:graphicImage value="#{img}" width="40" height="50" />
</h:panelGrid>
</p:column>
</p:dataGrid>
</p:outputPanel>
</h:form>
</div>
<div class="dialog-bottom-reg"></div>
</p:dialog>
#Named
#Scope("request")
public class DreamSearch extends BaseAction {
#Inject
DreamService dreamService;
#Inject
ImageSearchService flickrSearchImpl;
#Inject
private DreamSearchBean dreamSearchBean;
private UIForm dreamSearchFrm;
public void init(){
if (!FacesUtils.isPostback()) {
dreamSearchBean.setShouldRender(false);
dreamSearchBean.setSearchText(null);
}
}
public void setDreamSearchFrm(UIForm dreamSearchFrm) {
this.dreamSearchFrm = dreamSearchFrm;
init();
}
public void search(ActionEvent e){
try {
if(dreamSearchBean.getSearchText() != null && !dreamSearchBean.getSearchText().isEmpty()){
List<String> searchResults = flickrSearchImpl.searchByKeyWord(dreamSearchBean.getSearchText());
dreamSearchBean.setImages(searchResults);
dreamSearchBean.setShouldRender(true);
}else{
dreamSearchBean.setShouldRender(false);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void close(CloseEvent e){
dreamSearchBean.setShouldRender(false);
dreamSearchBean.setSearchText(null);
}
public UIForm getDreamSearchFrm() {
return dreamSearchFrm;
}
}
#Named
#Scope("session")
public class DreamSearchBean extends BaseSessionBean {
private List<String> images;
private String searchText;
private boolean shouldRender;
public String getSearchText() {
return searchText;
}
public void setSearchText(String searchText) {
this.searchText = searchText;
}
public boolean isShouldRender() {
return shouldRender;
}
public void setShouldRender(boolean shouldRender) {
this.shouldRender = shouldRender;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
}
Don't really know what the reason for this behavior is, but you could try the following:
For the <p:outputPanel id="searchPnl">: try to set the rendered tag on the panel and not on the h:outputText and p:dataGrid.
For the searchText try to update the <p:outputPanel id="searchTxtPnl"> instead of the h:inputText.
I noticed that the scope of your bean is request. If your doing ajax updates this really needs to be a ViewScoped bean with the JSF #ManagedBean and #ViewScoped annotations.
Another thing: make sure your not updating the form where the dialog resides in. This could have unwanted results.

Resources