I'm new to JSF. In my case I want to display several tables (for that purpose I'm using datalist - number of tables will known at runtime) and in each datatable row I need to execute some handler after checkbox has been checked (without any submit button - it will called later).
In code below
<f:ajax listener="#{dataListTry.run(o)}" event="change" render="some_datatable_id"/>
will be called after button have been submitted, but I need to refresh after checkbox will be checked, without submitting button. If I use datatable without datalist, callback calls without any problem.
How can I make callback works in datatable which is in datalist ?
Example of code:
<?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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:t="http://myfaces.apache.org/tomahawk"
>
<h:body>
<h:form id="some_example_form">
<t:dataList id="some_data_list"
var="dataListTry"
value="#{packageGroups.packageGroupList}" rowIndexVar="pos">
<t:div>
<t:outputLabel title="label"/>
<t:outputText value="Table_#{pos}"/>
</t:div>
<t:selectBooleanCheckbox title="External">
<f:ajax event="change" listener="#{dataListTry.run}" render=":some_example_form"/>
</t:selectBooleanCheckbox>
<t:column>
<t:dataTable id="some_datatable_id"
forceId="true"
forceIdIndex="true"
value="#{dataListTry.packageItems}"
var="o">
<t:column>
<h:outputText value="#{o.prefix}"/>
</t:column>
<t:column defaultSorted="false" sortable="false" width="28px">
<t:selectBooleanCheckbox value="#{o.selected}">
<f:ajax render="some_datatable_id"/>
<f:ajax event="change" listener="#{dataListTry.run(o)}"/>
</t:selectBooleanCheckbox>
</t:column>
</t:dataTable>
</t:column>
</t:dataList>
<br/>
<h:commandButton value="Submit" action="demo" forceId="true"/>
<h:commandButton value="MoveBack" action="demo" forceId="true" actionListener="#{packageGroups.moveBack()}"/>
</h:form>
</h:body>
</html>
And beans are:
PackageItem:
#ManagedBean(name = "packageItem")
#SessionScoped
public class PackageItem {
public boolean selected;
public String prefix;
public PackageItem(String prefix) {
this.prefix = prefix;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
setPrefix("selected after submit");
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
PackageGroup:
#ManagedBean(name = "packageGroup")
#SessionScoped
public class PackageGroup {
private List<PackageItem> packageItems;
private int value;
private String idGroup;
private String resultValue = "Created";
public PackageGroup(String groupId, int groupName, String value, String value2) {
this.idGroup = groupId;
this.value = groupName;
packageItems = new ArrayList<>();
packageItems.add(new PackageItem(value));
packageItems.add(new PackageItem(value2));
}
public PackageGroup() {
}
public List<PackageItem> getPackageItems() {
return packageItems;
}
public void setPackageItems(List<PackageItem> packageItems) {
this.packageItems = packageItems;
}
public void run() {
doClickAction();
}
public void run(PackageItem p) {
doClickAction();
this.resultValue = p.prefix;
}
private void doClickAction() {
packageItems.forEach(e -> e.setPrefix("selected!"));
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
PackageGroups:
#ManagedBean(name = "packageGroups")
#SessionScoped
public class PackageGroups {
private List<PackageGroup> packageGroupList;
public PackageGroups() {
packageGroupList = new ArrayList<>();
packageGroupList.add(new PackageGroup("100", -1, "one", "two"));
packageGroupList.add(new PackageGroup("200", -2, "three", "four"));
}
public void moveBack() {
packageGroupList.clear();
packageGroupList.add(new PackageGroup("100", -1, "one", "two"));
packageGroupList.add(new PackageGroup("200", -2, "three", "four"));
}
public List<PackageGroup> getPackageGroupList() {
return packageGroupList;
}
public void setPackageGroupList(List<PackageGroup> packageGroupList) {
this.packageGroupList = packageGroupList;
}
}
Generated html (only the view - it won't work on stackoverflow):
<?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"><body>
<form id="some_example_form" name="some_example_form" method="post" action="/JavaServerFaces_war_exploded/faces/demo.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="some_example_form" value="some_example_form" />
<div><label title="label">
</label>Table_0</div><script type="text/javascript" src="/JavaServerFaces_war_exploded/faces/javax.faces.resource/jsf.js?ln=javax.faces&stage=Development"></script><input id="some_example_form:some_data_list:0:j_idt8" type="checkbox" name="some_example_form:some_data_list:0:j_idt8" value="true" onchange="mojarra.ab('some_example_form:some_data_list:0:j_idt8',event,'change',0,'some_example_form')" title="External" />
<table id="some_datatable_id[0]">
<tbody id="some_datatable_id[0]:tbody_element">
<tr><td>one</td><td width="28px"><input id="some_datatable_id[0]:0:j_idt13" type="checkbox" name="some_datatable_id[0]:0:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[0]:0:j_idt13'), event,'mojarra.ab(\'some_datatable_id[0]:0:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[0]:0:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[0]\')'); return false;" /></td></tr>
<tr><td>two</td><td width="28px"><input id="some_datatable_id[0]:1:j_idt13" type="checkbox" name="some_datatable_id[0]:1:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[0]:1:j_idt13'), event,'mojarra.ab(\'some_datatable_id[0]:1:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[0]:1:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[0]\')'); return false;" /></td></tr>
</tbody></table>
<div><label title="label">
</label>Table_1</div><input id="some_example_form:some_data_list:1:j_idt8" type="checkbox" name="some_example_form:some_data_list:1:j_idt8" value="true" onchange="mojarra.ab('some_example_form:some_data_list:1:j_idt8',event,'change',0,'some_example_form')" title="External" />
<table id="some_datatable_id[1]">
<tbody id="some_datatable_id[1]:tbody_element">
<tr><td>three</td><td width="28px"><input id="some_datatable_id[1]:0:j_idt13" type="checkbox" name="some_datatable_id[1]:0:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[1]:0:j_idt13'), event,'mojarra.ab(\'some_datatable_id[1]:0:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[1]:0:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[1]\')'); return false;" /></td></tr>
<tr><td>four</td><td width="28px"><input id="some_datatable_id[1]:1:j_idt13" type="checkbox" name="some_datatable_id[1]:1:j_idt13" value="true" onchange="jsf.util.chain(document.getElementById('some_datatable_id[1]:1:j_idt13'), event,'mojarra.ab(\'some_datatable_id[1]:1:j_idt13\',event,\'change\',0,0)', 'mojarra.ab(\'some_datatable_id[1]:1:j_idt13\',event,\'valueChange\',0,\'some_datatable_id[1]\')'); return false;" /></td></tr>
</tbody></table>
<br /><input type="submit" name="some_example_form:j_idt15" value="Submit" /><input type="submit" name="some_example_form:j_idt16" value="MoveBack" /><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-6485444455087447596:-6234064892138587883" autocomplete="off" />
</form></body>
</html>
In posted html view if you check at the checkbutton under Table_% it will execute and change names of other two checkboxes (for example, if you check Table_0 one and two will change their names).
But if you check checkboxes near, for example, one and two, they will change their names only after executing button submit, but I need to get them changed after I clicked on them without
need to call button submit.
Finally found the solution. If forceId and forceIdIndex wouldn't set to true, then the ajax callback works.
I am trying to do some work when the h:commandButton is clicked. I am using jsf 2.2 as I am sending multipart data. I have 3 commandButtons in my form, The first 2 are working fine whereas the 3rd commandButton is not working.
This is my jsf page code:
<h:form id="userSetup" enctype="multipart/form-data" >
<div style=" margin-left: 250px; padding-top: 10px;width: 150px;margin-top: 100px;">
<img id="profile-picture" src="http://www.aspirehire.co.uk/aspirehire-co-uk/_img/profile.svg" height="120" width="120"></img>
<button onclick="addProfilePicture();return false;" class="cff-button" style="margin-top: 10px;margin-left: -10px;white-space: normal;width: 150px;">Add Profile Picture</button>
</div>
<br/><br/>
<h:inputFile id="profilePicture" value="#{uploader.profilePicture}" a:hidden="true" onchange="displayImage(this)">
<f:validator validatorId="imageValidator"></f:validator>
</h:inputFile>
<div class="user-input-div">
<h:messages id="response-message" style="color: red"></h:messages>
<h:inputText id="skills" a:placeholder="Skills" class="cff-inputText " ></h:inputText>
<br/><br/>
<button class="cff-button " style=" white-space: normal" onclick="toggleCertificateInput('#{certificateInput.clientId}',true);return false">Add Certificate</button>
<br/><br/>
<h:panelGroup id="certificate-input" layout="block" binding="#{certificateInput}" a:hidden="true" >
<h:inputText id="certificateName" value="#{uploader.certificateName}" class="cff-inputText" a:required="true" a:placeholder="Certificate Name" binding="#{certificateName}">
<f:validator validatorId="stringValidator"></f:validator>
</h:inputText>
<h:inputText id="certificateLink" value="#{uploader.certificateLink}" class="cff-inputText" a:placeholder="Link" binding="#{certificateLink}">
<f:validator validatorId="urlValidator"></f:validator>
</h:inputText>
<h:commandButton value="Save Certificate" class="cff-button" action="#{uploader.saveCertificate()}" >
<f:ajax execute="certificateName certificateLink response-message" onevent="function hide(data){ if(data.status === 'success'){ toggleCertificateInput('#{certificateInput.clientId}',false) } }" render="userSetup:certificate-output certificateName certificateLink response-message"></f:ajax>
</h:commandButton>
<button class="cff-button" onclick="toggleCertificateInput('#{certificateInput.clientId}',false);return false">Cancel</button>
</h:panelGroup>
<h:panelGroup id="certificate-output-div" binding="#{certificateOutput}">
<h:dataTable var="certificate" id="certificate-output" value="#{uploader.certificates}">
<h:column>
<h:outputText id="certificate-output-name" value="#{certificate.certificateName} " class="certificate-name"></h:outputText>
<h:outputLink id="certificate-output-link" class="cff-link" value=" #{certificate.link}">view certificate</h:outputLink>
<span id="remove" onclick="removeCertificate('#{removeCertificate.clientId}');" class="remove"> ×</span>
<h:commandButton a:hidden="true" binding="#{removeCertificate}" id="removeCertificate" action="#{uploader.removeCertificate(certificate)}" value="Remove" class="cff-button" >
<f:ajax execute=" certificate-output certificate-output-link certificate-output-name " render="userSetup:certificate-output response-message"></f:ajax>
</h:commandButton>
</h:column>
</h:dataTable>
</h:panelGroup>
//This command button is not working
<h:commandButton class="cff-button" action="#{uploader.saveAndContinue()}" value="Save and Continue">
<f:ajax execute="#form"></f:ajax>
</h:commandButton>
</div>
</h:form>
This is my model code:
#ManagedBean(name="uploader")
#ViewScoped
public class userDataUploader {
private String about_Yourself;
private String skills;
private List<Certificates> certificates;
private Part profilePicture;
private String certificateName;
private String certificateLink;
#ManagedProperty(value="#{userData}")
private User userData;
#PostConstruct
public void init(){
certificates = new ArrayList<Certificates>();
}
public List<Certificates> getCertificates() {
return certificates;
}
public void setCertificates(List<Certificates> certificates) {
this.certificates = certificates;
}
public Part getProfilePicture() {
return profilePicture;
}
public void setProfilePicture(Part profilePicture) {
this.profilePicture = profilePicture;
}
public String getAbout_Yourself() {
return about_Yourself;
}
public void setAbout_Yourself(String about_Yourself) {
this.about_Yourself = about_Yourself;
}
public String getSkills() {
return skills;
}
public void setSkills(String skills) {
this.skills = skills;
}
public User getUserData() {
return userData;
}
public void setUserData(User userData) {
this.userData = userData;
}
public String getCertificateName() {
return certificateName;
}
public void setCertificateName(String certificateName) {
this.certificateName = certificateName;
}
public String getCertificateLink() {
return certificateLink;
}
public void setCertificateLink(String certificateLink) {
this.certificateLink = certificateLink;
}
public void addCertificate(){
out.println("about to add new Certificate");
}
public void removeCertificate(Certificates certificate){
out.println("about to remove certificate " + certificate.getCertificateName() + " " + certificate.getLink() );
certificates.remove(certificate);
out.println(certificates.isEmpty());
}
public void saveCertificate(){
Certificates certificate = new Certificates();
certificate.setCertificateName(certificateName);
out.println(certificateName + "\n" + certificateLink);
certificate.setLink(certificateLink);
certificates.add(certificate);
out.println("new certificate has been added");
certificateName = null;
certificateLink = null;
out.println(certificates.isEmpty());
}
public String saveAndContinue(){
out.println("welcome to save and continue function");
out.println(skills);
boolean result = true;
Uploader uploader = new Uploader(userData,certificates,getSkillsArray(),profilePicture);
String returnString = "success";
out.println("about to save all data");
try {
uploader.saveAllData();
} catch (Exception ex) {
out.println(ex);
result = false;
}
if(!result){
returnString = "false";
}
out.println("return string is " + returnString);
return returnString;
}
private String[] getSkillsArray(){
return skills.split(" ");
}
}
Can somebody please tell me where I am going wrong? ThankYou.
I'm still learning how to use Facelets and I am trying to send inputted values from a JSF page to a list in a ManagedBean and then display that information in a dataTable. I have JSF page to enter in the data, a backing bean to manage the list, and a regular application for the normal objects. I can't figure out how to send the input value from the JSF to the backing bean, however.
Here is my view:
<?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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Guestbook Form</title>
</h:head>
<h:body>
<h:form>
<h1>Guestbook Application Form</h1>
<p>Please fill out all entries and click the Submit button</p>
<h:panelGrid columns="3">
<h:outputText value = "Name: "></h:outputText>
<h:inputText id="nameInputText" required ="true"
requiredMessage="Please enter your name"
value = "#{guestbookBean.name}"
validatorMessage="Name must be fewer than 20
characters">
<f:validateLength maximum="20"/>
</h:inputText>
<h:message for="nameInputText" styleClass="error"/>
<h:outputText value = "Email: "></h:outputText>
<h:inputText id="emailInputText" required ="true"
requiredMessage="Please enter your email address"
value="#{guestbookBean.email}"
validatorMessage="Invalid email address format">
<f:validateRegex pattern ="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
</h:inputText>
<h:message for="emailInputText" styleClass="error"/>
<h:outputText value = "Enter a message: "></h:outputText>
<h:inputTextarea id="messageInputText" required ="true"
requiredMessage="Please enter a message"
value="#{guestbookBean.message}"
validatorMessage="Message must be fewer than 140 characters">
<f:validateLength maximum="140"/>
</h:inputTextarea>
<h:message for="messageInputText" styleClass="error"/>
</h:panelGrid>
<h:commandButton value="Submit" type ="Submit" action ="#{guestbookBean.setList()}"/>
<h:commandButton value ="Reset Form" type ="reset"/>
<h:outputText escape="false" value ="#{guestbookBean.result}"/>
<h:dataTable value="#{guestbookBean.list}" var="guests"
styleClass="table" cellpadding="5" cellspacing="1" border="2">
<h:column>
<f:facet name ="header">Name</f:facet>
#{guests.name}
</h:column>
<h:column>
<f:facet name ="header">Email</f:facet>
#{guests.email}
</h:column>
<h:column>
<f:facet name ="header">Message</f:facet>
#{guests.message}
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
Here is my backing bean:
package guestbook;
import java.util.List;
import java.util.ArrayList;
import java.io.Serializable;
import javax.enterprise.context.Dependent;
import javax.faces.bean.*;
#ManagedBean(name = "guestbookBean")
public class GuestbookBean implements Serializable{
private String na;
private String em;
private String m;
private List<GuestbookEntry> bookList = new ArrayList<>();
//Set name
public void setName(String first)
{
this.na = first;
}
//Set email
public void setEmail(String mail)
{
this.em = mail;
}
//Set message
public void setMessage(String msg)
{
this.m = msg;
}
//Return the name
public String getName()
{
return na;
}
//Return the email
public String getEmail()
{
return em;
}
//Return the message
public String getMessage()
{
return m;
}
public void setList()
{
GuestbookEntry bk = new GuestbookEntry();
bk.setName(na);
bk.setEmail(em);
bk.setMessage(m);
bookList.add(0, bk);
}
public List<GuestbookEntry> getList()
{
return bookList;
}
// returns result for rendering on the client
public String getResult()
{
if ( !bookList.isEmpty())
{
return "<p style=\"background-color:yellow;width:200px;" +
"padding:5px\">Data submitted successfully"+ "</p>";
}
else
{
return ""; // request has not yet been made
}
} // end method getResult
}
Here is my model:
package guestbook;
public class GuestbookEntry {
private String firstName;
private String lastName;
private String email;
private String message;
public void setFirstName(String fn)
{
firstName = fn;
}
public void setLastName(String ln)
{
lastName = ln;
}
public void setEmail(String em)
{
email = em;
}
public void setMessage(String m)
{
message = m;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getEmail()
{
return email;
}
public String getMessage()
{
return message;
}
}
The data is not being reset because you are not clearing the fields after the submit
You can set to null na, em and m to reset the fields
Regarding the table, try adding #ViewScoped to your bean, the default scope is RequestScope, which is not keeping your table
In JSF2 - I see my datatable reloading each time when i make an ajax call by clicking on each column row. Is there a way to stop loading each time i make an ajax call ? This creates problem by resetting my datatable to default values and i get a wrong value back at managed bean.
<h:inputText size="8" id="startDate"
value="#{contactBean.startDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:outputText> - </h:outputText>
<h:inputText size="8" id="endDate" value="#{contactBean.endDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:commandButton value="Filter"
actionListener="#{contactBean.loadAJAXFilterContentList}">
<f:ajax render=":form1:tableContents" />
</h:commandButton>
<h:dataTable id="tableContents"
value="#{contactBean.filterContentList}" var="crs"
binding="#{contactBean.dataTable}" border="1">
<h:column>
<f:facet name="header">
<h:outputText styleClass="contactTableHeader" value="Date/Time" />
</f:facet>
<h:commandLink action="#{contactBean.loadPreviewScreenContents(crs)}">
<h:outputText title="#{crs.dateTime}" value="#{crs.dateTime}">
<f:convertDateTime pattern="MM/dd/yyyy hh:mm a" type="date" />
</h:outputText>
<f:ajax render=":form1:previewScreen" />
</h:commandLink>
</h:column>
</h:dataTable>
<h:panelGrid id="previewScreen">
<h:outputText styleClass="PreviewHeader"
value="Preview of #{contactBean.previewCntDateTime}" />
</h:panelGrid>
So in the above case whenever i click the column it calls the filterContentList() method in my managed bean instead of calling loadPreviewScreenContents(crs) directly.
My bean is RequestScoped. I tried with SessionScope,ViewScope but these 2 scopes retain my previous states like i have other ajax functions in my page and it retains that state. So i cant use Session or ViewScopes in this case.
Is there a solution ?
Bean code:
#ManagedBean(name = "contactBean")
#RequestScoped
public class ContactManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
List<ContactResponseBean> filterContentList = new ArrayList<ContactResponseBean>();
ContactRequestBean contactRequestBean = new ContactRequestBean();
ContactResponseBean crs = new ContactResponseBean();
private String logText;
HtmlDataTable dataTable;
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public Date getPreviewCntDateTime() {
return previewCntDateTime;
}
public void setPreviewCntDateTime(Date previewCntDateTime) {
this.previewCntDateTime = previewCntDateTime;
}
public String getLogText() {
return logText;
}
public void setLogText(String logText) {
this.logText = logText;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public ContactResponseBean getCrs() {
return crs;
}
public void setCrs(ContactResponseBean crs) {
this.crs = crs;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public void loadAJAXFilterContentList() {
filterButtonAjxFlag = true;
}
public List<ContactResponseBean> getFilterContentList() {
ContactRequestBean contactRequestBean = new ContactRequestBean();
contactRequestBean.setUserId(getUserId());
contactRequestBean.setSummaryType(getSummaryType());
contactRequestBean.setStartDate(getStartDate());
contactRequestBean.setEndDate(getEndDate());
ContactRequestBeanService crbs = new ContactRequestBeanService();
filterContentList = crbs.getFilterContentList(contactRequestBean);
return filterContentList;
}
public void loadPreviewScreenContents(){
crs = (ContactResponseBean) dataTable.getRowData();
setPreviewCntDateTime(crs.getDateTime());
}
}
I want to display details about a product when a user clicks on a link with the name of that product.
When debugging my code I see that the details method shown in the code below doesn't run.
My code:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
<ui:composition template="/Shared/layout.xhtml" >
<ui:define name="title">Product</ui:define>
<ui:define name="body">
<div id="contents" >
<h3> List Product in Site </h3>
<ul>
<ui:repeat value="#{productBean.listProduct}" var="p">
<div id="list-item">
<div class='item' >
<div class='item-img' >
<h:form>
<input type="hidden" name="productId" value="#{p.productId}" />
<h:commandLink action="#{productBean.details}">
<h:graphicImage url="#{p.picture}" alt='No Picture' />
</h:commandLink>
</h:form>
</div>
<h:form>
<input type="hidden" name="productId" value="#{p.productId}" />
<h:commandLink value="#{p.name}" action="#{productBean}" >
</h:commandLink>
</h:form>
</div>
</div>
</ui:repeat>
</ul>
<h:form>
<h:commandLink value="text" action="#{productBean.test}"> <!-- test -->
</h:commandLink>
</h:form>
</div>
</ui:define>
</ui:composition>
</h:body>
ProductBean:
#ManagedBean
#RequestScoped
public class ProductBean implements Serializable {
private List<Products> listProduct;
private List<Categories> listCategory;
private Products product;
public Products getProduct() {
return product;
}
public void setProduct(Products product) {
this.product = product;
}
public ProductBean() {
listCategory = new ProductsDB().listCategory();
}
private int categoryId;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String listProductByCt() {
try {
String value = FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap().get("categoryId");
setCategoryId(Integer.parseInt(value));
if (categoryId == 0) {
return "index";
}
listProduct = new ProductsDB().listProducts(categoryId);
return "product";
} catch (Exception e) {
return "error";
}
}
public String details() {
String s = "";
try {
String productId = FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap().get("productId");
if (productId != null) {
product = new ProductsDB().getProductById(productId);
return "details";
}
} catch (Exception e) {
return "error";
}
return "error";
}
public String test()
{
return "s";
}
public List<Categories> getListCategory() {
return listCategory;
}
public void setListCategory(List<Categories> listCategory) {
this.listCategory = listCategory;
}
public List<Products> getListProduct() {
return listProduct;
}
public void setListProduct(List<Products> listProduct) {
this.listProduct = listProduct;
}
}
I've also tried with another method called test. This too is referenced from an action on products.xhtml, but that action isn't placed inside a <ui:repeat>. In this case, the method does gets executed.
The test method:
public String test() {
String productId = "IP16G";
product = new ProductsDB().getProductById(productId);
return "details";
}
Which version of JSF are you using?
The code you've shown with different forms and hidden inputs inside a ui:repeat is not really idiomatic JSF. There's also a typo in the action of your first command link. It says produtBean but I guess it should be productBean. JSF will give you an exception though if you click on that command link.
Did you got that exception, or did nothing happen?
In case nothing happened, a likely cause is that the data you used to render your command links (#{productBean.listProduct}) is not available anymore after the post back. What method are you using to obtain this data and what is the scope of your bean? In many cases you should be using #ViewScoped and initialize the data when the request is not a post back.
Also, make sure there is no parent component of the <ui:repeat> that has a rendered attribute that is set to false by default. In case this attribute will be set to true at some point of the life-cycle, this may well be -after- the click on the link is processed. If that happens, it will still be false when the click is being processed, which has the effect that it will silently be ignored.
You can test the last effect by putting your test command link right next to the <ui:repeat>:
<ui:repeat value="#{productBean.products}" var="product">
...
</ui:repeat>
<h:commandLink value="test" action="#{productBean.test}" />
Although your approach with the multiple forms and hidden fields does work, a more idiomatic JSF version would be:
<h:form>
<ui:repeat value="#{productBean.products}" var="product">
<h:commandLink action="#{productBean.details(product)}">
<h:graphicImage url="#{product.picture}" alt="No Picture" />
</h:commandLink>
<h:commandLink value="#{product.name}" action="#{productBean.details(product)}" />
</ui:repeat>
</h:form>
With your bean's details method as:
public String details(Product product) {
this.product = product;
return "details";
}
(getting more off-topic, but if all your method does is returning a navigation case, you might want to consider using a direct link like <h:link> with the Id of your product as a parameter. This will use GET to go to your destination page, which in this case is much cleaner)
EDIT
In order to test whether the problem isn't somewhere else, try the following code. It's a single page and a single backing bean. Add these to your project and request the page. This should work.
forminloop.xhtml:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
<ui:repeat value="#{formInLoopBacking.items}" var="item">
<h:form>
<h:commandLink value="#{item}" action="#{formInLoopBacking.action}"/>
</h:form>
</ui:repeat>
</h:body>
</html>
FormInLoopBacking.java
import javax.faces.bean.ManagedBean;
#ManagedBean
public class FormInLoopBacking {
private String[] items = {"A", "B"};
public String[] getItems() {
return items;
}
public void action() {
System.out.println("Action called");
}
}
By looking at your above code
you have open <ui:repeat> tag but not closed it and try to put whole <ui:repeat> inside a form and check on your page is a <h:form> tag inside a h:form. If its not work then check your bean is in view scope or not if not put in view scope.