h:selectOneMenu along with f:selectItems always returns 0 - jsf

Here's my XHTML code:
<h:selectOneMenu id="combo" value="#{TeamsHinzufuegenBean.selectedLeagueId}">
<f:selectItems value="#{TeamsHinzufuegenBean.leagues}"
var="league" itemValue="#{league.id}"
itemLabel="#{league.name}"/>
</h:selectOneMenu>
And my bean:
#ManagedBean(name = "TeamsHinzufuegenBean")
#ViewScoped
public class TeamsHinzufügenBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<League> leagues;
private ArrayList<Team> teams = new ArrayList<Team>();
private String teamname;
private int selectedLeagueId=1;
#PostConstruct
public void init() {
leagues = Database.getInstance().getAllLeagues();
for(League l : leagues)
System.out.println(l);
}
public List<League> getLeagues() {
return leagues;
}
public void setLeagues(List<League> leagues) {
this.leagues = leagues;
}
public int getSelectedLeagueId() {
return selectedLeagueId;
}
public void setSelectedLeagueId(int selectedLeagueId) {
this.selectedLeagueId = selectedLeagueId;
}
public ArrayList<Team> getTeams() {
return teams;
}
public void setTeams(ArrayList<Team> teams) {
this.teams = teams;
}
public String getTeamname() {
return teamname;
}
public void setTeamname(String teamname) {
this.teamname = teamname;
}
}
The league-class has an attribute id but if I output the value of selectedLeagueId, it is always 0.

Check if getAllLeagues() contains objects that have an id and that it is correctly set

Related

nested <p:selectOneMenu does not update value

I have two selectOneMenu one update the other, but the second one do not update its value, and still remains with the first value, despite in any code, this two variables are equal so themselves. Even the valueEventChangeListener returns the estados_eam value. Thanks guys, any help will be very appreciate. Best regards.
<h:outputText value="ESTADO:" />
<p:selectOneMenu id="estados_eam" value="#{estadosMB.clave}"
style="width:200px;" required="true">
<f:selectItem itemLabel="Seleccione un estado" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{estadosMB.estadosMap}" />
<p:ajax listener="#{municipiosMB.handleEstadosChange}" update="municipios_eam"/>
</p:selectOneMenu>
<p:message for="estados_eam" />
<h:outputText value="MUNICIPIO:" />
<p:selectOneMenu id="municipios_eam" valueChangeListener="#{municipiosMB.selectOneMenuListener}"
value="#{municipiosMB.idMunicipio}" label="Municipios"
converter="javax.faces.Integer" style="width:200px;" required="true">
<f:selectItem itemLabel="Seleccione un Municipio"
itemValue="#{null}" />
<f:selectItems value="#{municipiosMB.municipiosMap}" />
<p:ajax listener="#{municipiosMB.handleMunicipioSelectedChange}" />
</p:selectOneMenu>
<p:message for="municipios_eam" />
Bean code:
#ManagedBean(name = "municipiosMB")
#ViewScoped
public class MunicipiosMB implements Serializable {
/**
*
*/
private static final long serialVersionUID = 112312323213445L;
private static Logger logger = LoggerFactory.getLogger(MunicipiosMB.class);
#ManagedProperty(value = "#{MunicipiosService}")
private MunicipiosService municipioService;
#ManagedProperty(value = "#{estadosMB}")
private EstadosMB estadosMB;
private Map<String, String> municipiosMap;
private Municipio selectedMunicipio;
private String clave;
private Estados estado;
private Integer id;
private String nombre;
private String siglas;
private String estado_clave;
private Municipio municipio;
private Integer idMunicipio;
public void updateMunicipio(Municipio municipio) {
this.clave = municipio.getIdEstado().getClave();
this.id = municipio.getId();
this.nombre = municipio.getNombre();
this.setMunicipio(municipio);
}
public Municipio getMunicipio() {
return municipio;
}
public void setMunicipio(Municipio municipio) {
this.municipio = municipio;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public Estados getEstado() {
return estado;
}
public void setEstado(Estados estado) {
this.estado = estado;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getSiglas() {
return siglas;
}
public void setSiglas(String siglas) {
this.siglas = siglas;
}
public Municipio getSelectedMunicipio() {
return selectedMunicipio;
}
public void setSelectedMunicipio(Municipio selectedMunicipio) {
this.selectedMunicipio = selectedMunicipio;
}
public MunicipiosService getMunicipioService() {
return municipioService;
}
public void setMunicipioService(MunicipiosService municipioService) {
this.municipioService = municipioService;
}
public Map<String, String> getMunicipiosMap() {
return municipiosMap = municipioService.getMunicipiosByClaveEstado(estadosMB.getClave());
}
public void setMunicipiosMap(Map<String, String> municipiosMap) {
this.municipiosMap = municipiosMap;
}
public EstadosMB getEstadosMB() {
return estadosMB;
}
public void setEstadosMB(EstadosMB estadosMB) {
this.estadosMB = estadosMB;
}
public Integer getIdMunicipio() {
return idMunicipio;
}
public void setIdMunicipio(Integer idMunicipio) {
this.idMunicipio = idMunicipio;
}
public void handleEstadosChange() {
try {
if (estadosMB.getClave() != null || !estadosMB.getClave().equals("77")) {
this.idMunicipio=0;
logger.info(" valor muncipio "+ this.idMunicipio);
logger.info("La clave seleccionada es "+estadosMB.getClave());
this.setMunicipiosMap(municipioService.getMunicipiosByClaveEstado(estadosMB.getClave()));
logger.info("Clave Estado Seleccionado: " + estadosMB.getClave());
logger.info("Clave Municipio Seleccionado: " + this.idMunicipio);
} else {
this.idMunicipio=0;
this.setMunicipiosMap(new HashMap<String, String>());
}
} catch (NullPointerException e) {
logger.info("EstadosMB Null");
this.setMunicipiosMap(new HashMap<String, String>());
}
}
public void handleMunicipioSelectedChange() {
logger.info("municipio seleccionado:::::: "+this.getIdMunicipio());
logger.info("municipio seleccionado2:::::: "+this.getId());
}
public Municipio selectedMunicipio() {
return municipioService.getMunicipiosById(this.getId());
}
public void selectOneMenuListener(ValueChangeEvent event) {
//This will return you the newly selected
//value as an object. You'll have to cast it.
Object newValue = event.getNewValue();
logger.info("valor nuevo"+ newValue.toString());
//The rest of your processing logic goes here...
}
}
I don't have any idea, why it is happending here...My EstadosMB
#ManagedBean(name="estadosMB")
#ViewScoped
public class EstadosMB implements Serializable {
#ManagedProperty(value="#{EstadosService}")
private EstadosService estadosService;
private String clave = "";
private Map<String,String> estadosMap;
public EstadosService getEstadosService() {
return estadosService;
}
public void setEstadosService(EstadosService estadosService) {
this.estadosService = estadosService;
}
public Map<String, String> getEstadosMap() {
return estadosMap = estadosService.getEstadosMap();
}
public void setEstadosMap(Map<String, String> estadosMap) {
this.estadosMap = estadosMap;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
}
There are two solutions:
Update the menu in the listener method in the bean by adding this line:
RequestContext.getCurrentInstance().update("municipios_eam");
Use a p:remoteCommand to update the 2nd menu, so instead of:
<p:ajax listener="#{municipiosMB.handleEstadosChange}" update="municipios_eam"/>
use:
//the remoteCommand should be placed before the first menu
<p:remoteCommand name="updateMuncipios_eam" update="municipios_eam"/>
<h:outputText value="ESTADO:" />
//some more code
<p:ajax listener="#{municipiosMB.handleEstadosChange}" oncomplete="updateMuncipios_eam()/>

i can not access to my model's attributs in the dynaForm primefaces

my problem is that i can not access to my model's attributs in the dynaForm.
(i'm using spring jsf primfaces).
picture of my xhtml where i have the problem
thank you for help.
here is my code
public class Colonne {
private String nomColonne;
private String typeColonne;
private int index;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Colonne() {
super();
}
public Colonne(String nomColonne, String typeColonne, int i) {
super();
this.nomColonne = nomColonne;
this.typeColonne = typeColonne;
this.index=i;
}
public String getNomColonne() {
return nomColonne;
}
public void setNomColonne(String nomColonne) {
this.nomColonne = nomColonne;
}
public String getTypeColonne() {
return typeColonne;
}
public void setTypeColonne(String typeColonne) {
this.typeColonne = typeColonne;
}
}
here is my managedBean
public class MonBean implements Serializable{
private static final long serialVersionUID = -5773011533863117274L;
private GestionTableImpl gestionTable;
private Table table;
private DynaFormModel model;
public static long getSerialversionuid() {
return serialVersionUID;
}
public DynaFormModel initialize() {
System.out.println("1");
model = new DynaFormModel();
Colonne col = new Colonne("a","b",0 );
DynaFormRow row = model.createRegularRow();
row.addControl(col, "columnName");
row.addControl(col, "columnType");
row.addControl(col, "add");
col = new Colonne("c","d",1 );
row = model.createRegularRow();
row.addControl(col, "columnName");
row.addControl(col, "columnType");
row.addControl(col, "add");
col = new Colonne("e","f", 2);
row = model.createRegularRow();
row.addControl(col, "columnName");
row.addControl(col, "columnType");
row.addControl(col, "add");
return model;
}
public DynaFormModel getModel() {
return model;
}
public void setModel(DynaFormModel model) {
this.model = model;
}
public Table getTable() {
return table;
}
public void setTable(Table table) {
this.table = table;
}
}
You are assigning #{monBean.initialize()} to dynaForm value attribute, use #{monbean.model} instead.
Also, you have to change initialize method of MonBean class to return void, and annotate this method with #PostConstruct.
This way it won't fail when executing and your IDE wn't complain about it.

How can I use multiple value in Input text field JSF

In my xhtml there are 3 input field which calculate remaining day of two <p:calendar> dates. In next step I want to store calculated remaining day to MY DB.
<p:dataTable styleClass="vtable" editable="true" var="user"
editMode="cell" value="#{userBean.employeeList}">
<p:column styleClass="columntd" headerText="#{text['user.startedDate']}">
<p:calendar widgetVar="fromCal" value="#{vacationBean.vacation.beginDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.fromSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['user.finishedDate']}">
<p:calendar widgetVar="toCal" value="#{vacationBean.vacation.endDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.toSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['employee.remainingdays']}">
<p:inputText id="diff" styleClass="daysNumber"
value="#{dayDiffBean.diff}" />
</p:column>
</p:dataTable>
<h:commandButton styleClass="sndbutton1"
value="#{text['employee.send']}" action="#{vacationBean.addVac}"/>
I used value="#{dayDiffBean.diff} to get remaining day and now I also want to use my vacationbean to store remaingday to my db using like this : value="#{vacationBean.vacation.balanceDay}"
But I cant use 2 value in inputtext field like this:
<p:inputText value="dayDiffBean.diff" value1="vacationBean.vacation.balanceDay">
How can i solve this problem?
This is my vacation bean code:
#ManagedBean(name="vacationBean")
#ViewScoped
public class VacationBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Date vEndDate;
private boolean selected;
private Date vStartDate;
private Date createdDate;
private String isNobody;
Requestrelax vacation;
Employee e;
Calendar javaCalendar = null;
private short balanceDay;
#EJB
VacationLocal vacations;
#ManagedProperty(value="#{loginBean.userId}")
Integer userId;
#EJB
EmployeesLocal employees;
#PostConstruct
public void init(){
System.out.println("0");
//System.out.println("STATrtsg >> . "+ diff.getDiff());
vacation=new Requestrelax();
e=employees.getEmployee(userId);
vacation.setEmployee(e);
System.out.println("balanday is:"+balanceDay);
}
public void addVac(){
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
vacations.addEmployeeVacation(vacation);
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Employee getE() {
return e;
}
public void setE(Employee e) {
this.e = e;
}
public Requestrelax getVacation() {
return vacation;
}
public void setVacation(Requestrelax vacation) {
this.vacation = vacation;
}
public Date getvEndDate() {
return vEndDate;
}
public void setvEndDate(Date vEndDate) {
this.vEndDate = vEndDate;
}
public Date getvStartDate() {
return vStartDate;
}
public void setvStartDate(Date vStartDate) {
this.vStartDate = vStartDate;
}
public short getBalanceDay() {
return balanceDay;
}
public void setBalanceDay(short balanceDay) {
this.balanceDay = balanceDay;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getIsNobody() {
return isNobody;
}
public void setIsNobody(String isNobody) {
this.isNobody = isNobody;
}
}
And daydiffbean code :
#ManagedBean(name="dayDiffBean")
#SessionScoped
public class DayDiffBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Date from;
private Date to;
private String diff="";
private final long oneDay=1000*60*60*24;
public void fromSelected(SelectEvent event){
from=(Date) event.getObject();
calDiff();
}
public void toSelected(SelectEvent event){
to=(Date) event.getObject();
calDiff();
}
public void calDiff(){
if(from==null||to==null){
diff="N/A";
return;
}
diff=(to.getTime()-from.getTime())/oneDay+"";
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getFrom() {
return from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
}
From the code, one way to add balanceDay to your vacationBean is by passing the diff string as a parameter to addVac() method (notice action in the second line):
<h:commandButton styleClass="sndbutton1" value="#{text['employee.send']}"
action="#{vacationBean.addVac(dayDiffBean.diff)}"/>
Then, for your VacationBean.addVac():
// 'diff' is now being passed in as a parameter
public void addVac(String diff) {
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
// UPDATED
// so now you can set balanceDay
setBalanceDay(Short.parseShort(diff));
vacations.addEmployeeVacation(vacation);
}

JSF Updating a selectOneMenu based on another one

I'm new to JSF, and stuck in a problem.
I have a selectOneMenu for displaying the list of countries. When the user selects one of the country, there's another selectOneMenu having the cities (=regions in my case) should be auto-populated.
I tried several iterations for doing the same but didn't help.
Please let me know if anything else is also needed to help me. Would really appreciate it.
UPDATE:
Here's the code after adding listener:
<p:outputLabel for="countryRegistration">#{msg['country']}:</p:outputLabel>
<p:selectOneMenu id="countryRegistration" value="#{mbcActor.geoData.country}" style="width:120px;" >
<f:attribute name="country" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCountry']}" itemValue=""/>
<f:selectItems value="#{geoLists.countryList}" var="country" itemLabel="#{country.name}"/>
<p:ajax listener="#{mbcActor.geoData.updateRegions}" render="cityRegistration"/>
</p:selectOneMenu>
<p:message for="countryRegistration"/>
<p:outputLabel for="cityRegistration">#{msg['city']}:</p:outputLabel>
<p:selectOneMenu id="cityRegistration" value="#{mbcActor.geoData.region}" style="width:120px;">
<f:attribute name="regions" value="java.util.List" />
<f:converter converterId="ViewScopedObjectConverter"/>
<f:selectItem itemLabel="#{msg['selectCity']}" itemValue=""/>
<!--<f:selectItems value="#{geoLists.regionForCountry}" var="region" itemLabel="#{region.name}"/>-->
<f:selectItems value="#{geoLists.getRegionForCountry(country)}" var="region" itemLabel="#{region.description}"/>
</p:selectOneMenu>
<p:message for="cityRegistration"/>
But it says:
Oct 05, 2013 2:04:53 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: Target Unreachable, identifier 'mbcActor' resolved to null
javax.el.PropertyNotFoundException: Target Unreachable, identifier 'mbcActor' resolved to null
at org.apache.el.parser.AstValue.getTarget(AstValue.java:98)
at org.apache.el.parser.AstValue.invoke(AstValue.java:259)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processCustomListener(AjaxBehaviorListenerImpl.java:70)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processArgListener(AjaxBehaviorListenerImpl.java:59)
at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:47)
Beans:
package xxx.core.entities;
// Generated Oct 20, 2009 11:07:18 AM by Hibernate Tools 3.2.2.GA
import javax.faces.event.ValueChangeEvent;
import javax.inject.Inject;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
/**
* DataActorGeo
*/
#Entity
#Table(name = "dataActorGeo")
// #org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
#Access(AccessType.PROPERTY)
public class DataActorGeo implements java.io.Serializable {
private Integer id;
private Country country;
private Region region;
private String city;
private String province;
private String address;
private String addressLine2;
private String postCode;
private String nationality;
private String phone1;
private String phone2;
private Double latitude;
private Double longitude;
private Actor actor;
private List<Region> regions;
#Inject
EntityManager entityManager;
public void updateRegions() {
//Country ctry = (Country) event.getNewValue();
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
// if (regions == null) {
this.regions = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", country.getId())
.getResultList();
//countryIdCache = country.getId();
// }
System.out.println("aaaaaaaaaaa" + regions.toString());
} catch(Exception e){System.out.println("cccccccccc"); }//return new ArrayList<Region>(); }
//return regions;
}
public DataActorGeo() {
}
public DataActorGeo(Country country, String city) {
this.country = country;
this.city = city;
}
public DataActorGeo(Country country, Region region, String city, String address, String postCode, String phone1, String phone2, Actor actor) {
this.country = country;
this.region = region;
this.city = city;
this.address = address;
this.postCode = postCode;
this.phone1 = phone1;
this.phone2 = phone2;
this.actor = actor;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Country")
// #IndexedEmbedded(prefix = "country.")
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Region")
// #IndexedEmbedded(prefix = "region.")
public Region getRegion() {
return this.region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Region> getRegions()
{
return this.regions;
}
public void setRegions(List<Region> regions)
{
this.regions=regions;
}
#Column(name = "City")
// //#Field(index = Index.UN_TOKENIZED)
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "province")
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
#Column(name = "address")
// //#Field(index = Index.TOKENIZED)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "addressLine2")
// //#Field(index = Index.TOKENIZED)
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
#Column(name = "postCode")
// //#Field(index = Index.UN_TOKENIZED)
public String getPostCode() {
return this.postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#Column(name = "nationality")
// //#Field(index = Index.UN_TOKENIZED)
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
#Column(name = "phone1")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone1() {
return phone1;
}
public void setPhone1(String phone1) {
this.phone1 = phone1;
}
#Column(name = "phone2")
// //#Field(index = Index.UN_TOKENIZED)
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
#OneToOne(mappedBy = "geoData")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "latitude")
public Double getLatitude() {
return latitude;
}
#Column(name = "longitude")
public Double getLongitude() {
return longitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
package xxx.lists;
import xxx.application.configuration.ISNetApp;
import xxx.core.entities.Country;
import xxx.core.entities.Region;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Named
#ViewScoped
public class GeoLists implements Serializable {
#Inject
EntityManager entityManager;
#Inject
ISNetApp sNetApp;
private List<Country> countryList;
public List<Country> getCountryList() {
if (countryList == null) {
String query = "select c from Country c order by c.ordering, c.name";
countryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
private List<Country> deliveryCountryList;
public List<Country> getDeliveryCountryList() {
if (deliveryCountryList == null) {
String query = "select c from Country c where c.groups LIKE '%D,%' order by c.ordering, c.name";
deliveryCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return deliveryCountryList;
}
public void setDeliveryCountryList(List<Country> deliveryCountryList) {
this.deliveryCountryList = deliveryCountryList;
}
public Country getCountryByIsoCode2(String isoCode2) {
String query = "select c from Country c where c.isoCode2=:ic";
try {
return (Country) entityManager.createQuery(query).setParameter("ic", isoCode2).getSingleResult();
} catch (NoResultException e) {
return null;
}
}
private List<Region> regionForCountry;
private int countryIdCache;
private List<Region> regions;
public List<Region> getRegions(){
return this.regions;
}
public void setRegions(List<Region> regions){
this.regions = regions;
}
public List<Region> getRegionForCountryById(Long countryId) {
Country country = entityManager.find(Country.class, countryId.intValue());
return getRegionForCountry(country);
}
public List<Region> getRegionForCountry(Country country) {
try{
System.out.println("bbbbbbbbbbbbbbbbbbbbbbb" + country.toString());
//if (regionForCountry == null || countryIdCache != country.getId()) {
regionForCountry = entityManager.createQuery("select r From Region r Where r.country.id = :countryId order by r.description ")
.setParameter("countryId", 1)//country.getId())
.getResultList();
// countryIdCache = country.getId();
//}
// System.out.println("aaaaaaaaaaa" + regionForCountry.toString());
} catch(Exception e){System.out.println("cccccccccc"); return new ArrayList<Region>(); }
return regionForCountry;
}
public void setRegionForCountry(List<Region> regionForCountry) {
this.regionForCountry = regionForCountry;
}
private Country mainCountry;
private Country country;
public void setCountry(Country country) {
this.country=country;
}
public Country getCountry(){
return this.country;
}
public Country getMainCountry() {
if (mainCountry == null) {
mainCountry = entityManager.find(Country.class, sNetApp.getMainCountryId());
}
return mainCountry;
}
public void setMainCountry(Country mainCountry) {
this.mainCountry = mainCountry;
}
private List<Country> specificGroupCountryList;
private String groupCache;
public List<Country> getSpecificGroupCountryList(String group) {
if (specificGroupCountryList == null || groupCache == null || groupCache.compareTo(group) != 0) {
String query = "from Country where groups LIKE '%" + group + ",%' order by ordering, name";
specificGroupCountryList = (List<Country>) entityManager.createQuery(query).getResultList();
}
return specificGroupCountryList;
}
public void setSpecificGroupCountryList(List<Country> specificGroupCountryList) {
this.specificGroupCountryList = specificGroupCountryList;
}
}
mbcActor is a param defined as:
<ui:param name="mbcActor" value="#{registrationHelper.newActor}"/>
AbstractActor:
#MappedSuperclass
public class AbstractActor extends AbstractGenericElement implements java.io.Serializable, IGenericElement, EmailContact {
private static Logger log = LoggerFactory.getLogger(AbstractActor.class);
public static enum Gender {
Male,
Female
}
/**
* Transient
*/
private boolean selected;
private Integer id;
private Long version;
private byte type;
private String language;
private byte status;
private byte publicStatus;
private String permalink;
private Boolean customPermalink;
private String displayName;
private String forename;
private String surname;
private Gender gender;
private Date birthday;
private String mobile;
private Byte subType;
private String stringValue1;
private String stringValue2;
private String stringValue3;
#Transient
#XmlTransient
private Integer age;
private String profileMessage;
private String statusMessage;
private String email;
private String username;
private String passwordHash;
private int passwordHashIterations;
private String salt;
private String timezone;
private String activationCode;
private Boolean activationEmailSent;
private Integer completitionPercentage;
private Integer ordering;
// Stats
private ActorStats stats;
// Extensions
private DataActorGeo geoData;
private DataActorExtended dataActorExtended;
private Boolean acceptNewsletter;
private Boolean emailAlertsEnabled;
private Set<ActorTag> actorTags = new HashSet<ActorTag>(0);
private List<Role> roles = new ArrayList<Role>(0);
private Actor newDataToBeModerated;
private Date expireDate;
private Integer points;
private BigDecimal wallet;
private Byte emailAlertsType;
private Byte emailOffersType;
private String emailHash;
// Data blob
private byte[] data;
private Set<ActorInCategory> actorInCategories = new HashSet<ActorInCategory>(
0);
private List<ActorAttribute> actorAttributes = new ArrayList<ActorAttribute>(0);
public AbstractActor() {
this.version = 1l;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
public AbstractActor(byte type, byte status) {
this.version = 1l;
this.type = type;
this.status = status;
this.publicStatus = ActorConstants.PUBLIC_STATUS_OFFLINE;
this.activationEmailSent = false;
this.acceptNewsletter = true;
this.emailAlertsEnabled = true;
this.completitionPercentage = 0;
this.customPermalink = false;
this.wallet = new BigDecimal(0);
this.points = 0;
this.emailAlertsType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
this.emailOffersType = ActorConstants.RECURRING_EMAIL_TYPE_NONE;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "geoData", nullable = true)
#org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public DataActorGeo getGeoData() {
return this.geoData;
}
public void setGeoData(DataActorGeo geoData) {
this.geoData = geoData;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public Set<ActorInCategory> getActorInCategories() {
return this.actorInCategories;
}
public void setActorInCategories(Set<ActorInCategory> actorInCategories) {
this.actorInCategories = actorInCategories;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "actor")
public List<ActorAttribute> getActorAttributes() {
return this.actorAttributes;
}
public void setActorAttributes(List<ActorAttribute> actorAttributes) {
this.actorAttributes = actorAttributes;
}
}
Your <p:ajax> tag uses the render attribute, which isn't predefined. The attribute you want is update.
supposing that registrationHelper.newActor is an instance of of a Managed Bean, I think it's probably not initialized. Why don't you make sure it is, by creating it on RegistrationHelper's PostConstruct, or even get it through a method like
public AbstractActor createNewActor() {
newActor = new AbstractActor();
return newActor;
}
<ui:param name="mbcActor" value="#{registrationHelper.createNewActor}"/>

backing bean in jsf scope

I am displaying a ProductList, which is made up of Product objects. The Product has attributes of type int, string, string, and int. The data is being pulled from the database and I build a ProductList. The data is in the database, I can see it, but when I display the table, the table shows 0's for the 2 int columns, and blanks in the String columns. Here is the ProductList:
#ManagedBean
public class ProductList {
private ArrayList<Product> allProducts;
public ProductList(){
allProducts = DatabaseConnector.getAllProducts();
}
public ArrayList<Product> getAllProducts(){
return allProducts;
}
public void setAllProducts(ArrayList<Product> allProducts){
this.allProducts = allProducts;
}
}
And here is the Product bean:
#ManagedBean
public class Product {
private int id;
private String productName;
private String description;
private int quantity;
public Product() {
}
public void setId(int id) {
this.id = id;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setDescription(String description) {
this.description = description;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getId() {
return id;
}
public String getProductName() {
return productName;
}
public String getDescription() {
return description;
}
public int getQuantity() {
return quantity;
}
}
Should I change the scope of the beans?
Add scope annotation to your bean , for example #RequestScoped or #ViewScoped
otherwise it will be the default scope which is #NoneScoped

Resources