how to get id of selected item value from selectOneMenu in jsf? - jsf-2

I have dropdown of categories. On selecting particular category, I have rendered another dropdown of subcategories of that category. I want id of selected subcategory.But I am not getting it.My code is:
<tr>
<td align="right">
<h:outputText value="Select Main Category:"></h:outputText>
</td>
<td>
<h:selectOneMenu id="cmbcategory" value="#{categoryBean.categoryID}" required="true" requiredMessage="Select Category" >
<f:selectItem itemLabel="--Select Category--" itemValue="0"></f:selectItem>
<f:selectItems value="#{categoryBean.categories}" var="item" itemLabel="#{item.categoryName}" itemValue="#{item.categoryID}"></f:selectItems>
<f:ajax event="valueChange" render="cmbsubcategory" immediate="true" listener="#{categoryBean.SubcategoriesByCategory()}"/>
</h:selectOneMenu>
</td>
<td><h:message for="cmbcategory"></h:message></td>
</tr>
<tr>
<td align="right">
<h:outputText value="Select Sucategory:"></h:outputText>
</td>
<td>
<h:selectOneMenu id="cmbsubcategory" value="#{categoryBean.subCategoryID}" required="true" requiredMessage="Select Subcategory">
<f:selectItem itemLabel="--Select Subcategory--" itemValue="0"></f:selectItem>
<f:selectItems value="#{categoryBean.SubcategoriesByCategory()}" var="item" itemLabel="#{item.subcategoryID}" itemValue="#{item.subcategoryID}"></f:selectItems>
</h:selectOneMenu>
</td>
<td><h:message for="cmbsubcategory"></h:message></td>
</tr>
And my bean is:
public int getCategoryID() {
return CategoryID;
}
public void setCategoryID(int CategoryID) {
this.CategoryID = CategoryID;
}
public String getCategoryName() {
return CategoryName;
}
public void setCategoryName(String CategoryName) {
this.CategoryName = CategoryName;
}
public Collection<Category> getCategories() {
categories=abr.getAllCategory();
return categories;
}
public Collection<Subcategory> SubcategoriesByCategory()
{
System.out.print("catid...... "+CategoryID);
subcats= abr.searchAllSubcategoriesByCategory(CategoryID);
return subcats;
// +"size....."+ subcats.size());
}
public String getSubCatName() {
return SubCatName;
}
public void setSubCatName(String SubCatName) {
this.SubCatName = SubCatName;
}
public int getSubCategoryID() {
System.out.print("subcatid...... "+SubCategoryID);
return SubCategoryID;
}
public void setSubCategoryID(int SubCategoryID) {
this.SubCategoryID = SubCategoryID;
}
public Collection<Subcategory> getSubcats() {
return subcats;
}
public void setSubcats(Collection<Subcategory> subcats) {
this.subcats = subcats;
}
public void setCategories(Collection<Category> categories) {
this.categories = categories;
}

You are mixing up a property getter with an action method. A getter should return the property and an action method should be void or return a String.
Change
public Collection<Subcategory> SubcategoriesByCategory() {
..
}
to
public void searchSubcats() {
subcats= abr.searchAllSubcategoriesByCategory(CategoryID);
}
and call this method in your ajax request:
<f:ajax .. listener="#{categoryBean.searchSubcats}"/>
The selectItems in the second drow-down then need to reference the getter for subcats:
<f:selectItems value="#{categoryBean.subcats}" ... />

Related

How i can get value from s:checkbox

i want to get value from table using s:checkbox
i create this app using struts2
My code is as follows:
testAction.java
public class test extends ActionSupport{
private String id;
private List<String> colors;
private String yourColor;
public String getYourColor() {
return yourColor;
}
public void setYourColor(String yourColor) {
this.yourColor = yourColor;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getColors() {
return colors;
}
public void setColors(List<String> colors) {
this.colors = colors;
}
private List<ColorBean> list ;
public List<ColorBean> getList() {
return list;
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}
}
struts.xml
<action name="testAction" class="action.testAction" method="display">
<result name="none" type="tiles">index</result>
</action>
<action name="resultAction" class="action.testAction">
<result name="success">result.jsp</result>
</action>
index.jsp
<s:form action="resultAction" namespace="/">
<table id="dataTables-example">
<thead>
<tr>
<th>sheck</th>
<th>IF</th>
<th>CINOURC</th>
<th>NOMOURC</th>
</tr>
</thead>
<tbody>
<s:iterator value="list">
<tr>
<td>
<s:checkbox name="yourColor"
fieldValue="%{list}" theme="simple" />
</td>
<td><s:property value="id" /></td>
<td><s:property value="cin" /></td>
<td><s:property value="name" /></td>
</tr>
</s:iterator>
</tbody>
</table>
result.jsp
<h2>
value : <s:property value="yourColor"/>
</h2>
the problem is when i receive the value in result page i receive an object like
[bean.RarBean#42a3fe79, bean.RarBean#2d2cfd76, bean.RarBean#54e8f278]
and when i try to do something like this
<h2>
value : <s:property value="yourColor.id"/>
</h2>
i receive nothing ..
how i can handle this problem

jsf2 template component with parameter

I have a jsf template page. In this template i would like to use component with parameter. Actually i would like to iterate over collection. This collection should be determined by parameters from particular page. Parameter name is selectedMenu. How can i use this in my bean?
<div id="notes">
selectedMenu: #{selectedMenu}
<h:form>
<h:inputHidden value="#{notatkaController.searchForm.kategoria}">
<f:param value="#{selectedMenu}" />
</h:inputHidden>
<ui:repeat value="#{notatkaController.items}" var="item" varStatus="iter">
<f:param value="#{selectedMenu}" />
<p class="q-title"><strong><h:outputText value="#{item.ntaData}" /></strong></p>
<p class="answer"><h:outputText value="#{item.ntaDane}" escape="false" /></p>
</ui:repeat>
<span>Moje notatki</span>
<textarea>Tu wpisz treść swojej notatki</textarea>
<span>[+] dodaj notatkę</span>
</h:form>
</div>
My bean:
#ManagedBean(name = "notatkaController")
#ViewScoped
public class NotatkaController extends AbstractController<Notatka> implements Serializable {
#EJB
private pl.alfaprojekt.model.session.NotatkaFacade ejbFacade;
private NotatkaSearchForm searchForm;
public DataModel getItems() {
if (items == null)
items = getPagination().createPageDataModel();
return items;
}
public PaginationHelper getPagination() {
if (pagination == null) {
if (paginationSize == null)
paginationSize = 10;
pagination = new PaginationHelper(paginationSize) {
#Override
public int getItemsCount() {
return getFacade().countByParam(getSearchForm());
}
#Override
public DataModel createPageDataModel() {
if (rapId == null)
return new ListDataModel(getFacade().findRangeByParam(getSearchForm(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
else {
Long uzyId = SessionUtil.getUser().getUzyId();
return new ListDataModel(convertToRaportWierszList(getFacade().findRangeByParam(getSearchForm(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}), uzyId));
}
}
};
}
return pagination;
}
}
I am not sure I understood the question but the question I answer is this:
I want to dynamically display something. I want to tell it what to display when the page gets accessed.
View:
You could then use the following:
<f:event listener="#{myBean.myMethod}" type="preRenderView" />
Bean:
public void myMethod(ComponentSystemEvent event){
//your logic here
}
With parameter:
<f:metadata>
<f:event listener="#{myBean.myMethod}" type="preRenderView" id="fevent"/>
<f:attribute name="myParam" value="#{mySecondBean.param)" />
</f:metadata>
And
public void myMethod(ComponentSystemEvent event){
String id = (String) event.getComponent().getAttributes().get("myParam");
}

JSF 2 FacesConverter doesn't work with composite component

I've got simple composite component which has to render h:selectManyListbox with h:messages associated with it. The problem is with using faces converter class. It seems to be not working with it (only if used in component code).
Composite component code :
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:composite="http://java.sun.com/jsf/composite">
<!-- INTERFACE -->
<composite:interface>
<composite:attribute name="description" required="true" />
<composite:attribute name="fieldValue" required="true" />
<composite:attribute name="idc" required="true" />
<composite:attribute name="size" required="true" />
</composite:interface>
<!-- IMPLEMENTATION -->
<composite:implementation>
<tr>
<td nowrap="nowrap">
<h:outputText value="#{cc.attrs.description}" />
</td>
<td>
<h:selectManyListbox
id="#{cc.attrs.idc}"
size="#{cc.attrs.size}"
value="#{cc.attrs.fieldValue}">
<composite:insertChildren />
</h:selectManyListbox>
</td>
<td>
<h:message for="#{cc.attrs.idc}" />
</td>
</tr>
</composite:implementation>
</html>
When I use it on sample.xhtml page (as shown below), I get 'Validation Error: Value is not valid'.
.....
But when on the same page I put code like:
<tr>
<td><h:outputText value="Plugins" /></td>
<td>
<h:selectManyListbox
id="plugins"
value="#{bean.currentPlugins}"
size="6">
<f:selectItems value="#{bean.availablePlugins}" />
</h:selectManyListbox>
</td>
<td><h:message for="plugins" /></td>
</tr>
everything goes fine.
The managed bean 'bean' class is
#ManagedBean
#SessionScoped
public class Bean extends GenericManagedBean
implements Serializable {
ElementClass[] currentPlugins;
// getter & setter for currentPlugins
// ...
public List<ElementClass> getAvailablePlugins() {
// .. some code
return list;
}
}
and ElementClass is
public class ElementClass extends GenericEntity implements Serializable {
private static final long serialVersionUID = 9159873495276902436L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
// other fields
// ...
// getters & setters
// ...
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof ElementClass)) {
return false;
}
ElementClass other = (ElementClass) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
}
For the ElementClass I've got converter class
#FacesConverter(forClass = ElementClass.class)
public class ElementClassConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uiComponent,
String elemId) {
if (!StringUtils.isEmpty(elemId)) {
// this code gets ElementClass object entity from database
ApplicationBean applicationBean = JSFHelper
.findBean("applicationBean");
return applicationBean.getService()
.findElementClassById(
Integer.parseInt(elemId));
} else {
return null;
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uiComponent,
Object elem) {
return elem != null ? ((ElementClass ) elem).getId()
.toString() : "";
}
}
And standard question: what am I doing wrong? I assume this is my lack of knowledge rather than jsf implemenation bug. I use JBoss 7.1.1 AS and everything, what is bundled with it + RichFaces 4.

selectOneMenu validation error

I implemented code that allows me to display a dropdown which depends on another. Everything works fine except when I try to retrieve and display the value of the two fields, it raises the following error:
form:parcours : erreur : de validation. la valeur est incrorrecte
in english :
form:parcours : validation error. value is not valid
I am using JSF 2.0, EJB 3.0, JPA 2.0 and PrimeFaces 3.2.
View:
<h:form id="form" >
<!-- <p:growl id="msgs" showDetail="true"/> -->
<h:messages globalOnly="true"/>
<p:growl id="msgs" showDetail="true" />
<p:panel header="Double Combo" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:selectOneMenu id="countries" value="#{plansEtude.selectedDep}">
<f:selectItem itemLabel="Select Country" itemValue="" />
<f:selectItems value="#{plansEtude.depList}" var="c" itemLabel="#{c.nomDepFr}" itemValue="#{c.id}"/>
<p:ajax update="parcours,parcoursTab"
listener="#{plansEtude.handleDepChange}" />
</p:selectOneMenu>
<p:selectOneMenu id="parcours" value="#{plansEtude.selectedParcours}" >
<f:convertNumber maxFractionDigits="0"/>
<f:selectItem itemLabel="Select City" itemValue="" />
<f:selectItems value="#{plansEtude.parcoursList}" var="ct" itemLabel="#{ct.designParcours}" itemValue="#{ct.id}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<p:commandButton value="Submit" update="msgs" actionListener="#{plansEtude.displayLocation}" id="btnSubmit"/>
</p:panel>
Controller :
#EJB
private DepartementFacade departementFacade;
#EJB
private ParcoursFacade parcoursFacade;
private List<Departement> depList;
private List<Parcours> parcoursList;
private Integer selectedDep;
private Integer selectedParcours;
public PlansEtude() {
}
public DepartementFacade getDepartementFacade() {
return departementFacade;
}
public void setDepartementFacade(DepartementFacade departementFacade) {
this.departementFacade = departementFacade;
}
public ParcoursFacade getParcoursFacade() {
return parcoursFacade;
}
public void setParcoursFacade(ParcoursFacade parcoursFacade) {
this.parcoursFacade = parcoursFacade;
}
public List<Departement> getDepList() {
depList = getDepartementFacade().findAll();
return depList;
}
public void setDepList(List<Departement> depList) {
this.depList = depList;
}
public List<Parcours> getParcoursList() {
return parcoursList;
}
public void setParcoursList(List<Parcours> parcoursList) {
this.parcoursList = parcoursList;
}
public Integer getSelectedDep() {
return selectedDep;
}
public void setSelectedDep(Integer selectedDep) {
this.selectedDep = selectedDep;
}
public Integer getSelectedParcours() {
return selectedParcours;
}
public void setSelectedParcours(Integer selectedParcours) {
this.selectedParcours = selectedParcours;
}
public void handleDepChange(){
if(selectedDep !=null && !selectedDep.equals(""))
parcoursList = parcoursFacade.findParcoursInDep(selectedDep);
else
parcoursList = new ArrayList<Parcours>();
}
public void handleParcoursChange(){
}
public void displayLocation() {
String monMessage="Departement :" + selectedDep + ", Parcours : " + selectedParcours;
FacesMessage msg = new FacesMessage("Selected", monMessage);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
parcoursFacade :
public List<Parcours> findParcoursInDep(Integer dep){
Query query = em.createNamedQuery("Parcours.findParcoursInDep");
query.setParameter("dep", dep);
return (List<Parcours>)query.getResultList();
}
Named query :
#NamedQuery(name = "Parcours.findParcoursInDep", query = "SELECT p FROM Parcours p WHERE p.departementid.id = :dep"),
Remove the <f:convertNumber maxFractionDigits="0"/> from your parcours dropdown. It makes no sense. It would only convert the number to BigDecimal while you need an Integer.
Another possible cause is that the #{plansEtude.parcoursList} has incompatibly changed during the form submit because the managed bean is request scoped. You need to make sure that the managed bean is placed in at least the view scope, so that the parcoursList is preserved for the submit.

item selection from <h:selectOneMenu> does not change bean property

I face with situation, when item selection from does not change bean property. Method setCurrentOrg() does not invoked.
Managed bean code is:
#ManagedBean(name = "requestAccessBean")
#RequestScoped
public class RequestAccessSection {
private List<AccessRight> accessList;
private List<OrgUnit> orgList;
private String currentOrg;
public String getCurrentOrg() {
return this.currentOrg;
}
public void setCurrentOrg(String currentOrg) {
this.currentOrg = currentOrg;
}
public List<AccessRight> getAccessList() {
if (this.accessList == null) {
this.accessList = returnAccessList();
}
return this.accessList;
}
public void setAccessList(List<AccessRight> accessList) {
this.accessList = accessList;
}
public List<OrgUnit> getOrgList() {
if (this.orgList == null) {
this.orgList = returnOrgList();
}
return this.orgList;
}
public void setOrgList(List<OrgUnit> orgList) {
this.orgList = orgList;
}
public List<OrgUnit> returnOrgList() {
List<OrgUnit> orgList = new ArrayList<OrgUnit>();
orgList = getOfficeBranches();
return orgList;
}
public List<AccessRight> returnAccessList() {
List<AccessRight> accessList = new ArrayList<AccessRight>();
accessList = getAccessList();
return accessList;
}
}
Page is:
<h:form>
<h:selectOneMenu id="orgList" value="# {requestAccessBean.currentOrg}">
<f:selectItem itemLabel="--select--" itemValue="null"></f:selectItem>
<f:selectItems value="#{requestAccessBean.orgList}"
var="org" itemLabel="#{org.ou}" itemValue="#{org.globalid}"/>
<f:ajax event="change" execute="#this" render="accessTable"/>
</h:selectOneMenu>
<h:dataTable var="access" value="#{requestAccessBean.accessList}"
binding="#{requestAccessBean.htmlDataTable}" id="accessTable">
<h:column>
<h:selectOneRadio onclick="radioButton(this);" id="selectAccess"
valueChangeListener="#{requestAccessBean.setSelected}">
<f:selectItem itemValue="null" />
</h:selectOneRadio>
</h:column>
<h:column>
<h:outputText value="#{access.title}" />
</h:column>
</h:dataTable>
<h:form>
Could you please help me?
<h:selectOneMenu id="orgList" value="# {requestAccessBean.currentOrg}">
This is not valid EL. You have a space between # and {. Remove it.
<h:selectOneMenu id="orgList" value="#{requestAccessBean.currentOrg}">

Resources