Rendering elements in MyFaces 1.1.1 - jsf

I am trying to create a simple jsf page where I have a dropdown whose value determines which label to render. Initially all the labels' render is set as false through the backing bean constructor. But I have called submit onchange which sets the respective values to true for the labels. I have set the scope of the backing bean as session so that the value being set does not get removed onchange. However the label does not get rendered onchange. Below is the code snippet for the jsf page:
<h:form>
<h:panelGroup>
<h:outputLabel styleClass="captionOutputField" value="Select Report Type:" />
<h:selectOneMenu id="selectedMenu" onchange="submit()" valueChangeListener="#{ReportHealth.typeSelectDropDownChange}">
<f:selectItem itemLabel="" itemValue="empty" />
<f:selectItem itemLabel="daily" itemValue="daily" />
<f:selectItem itemLabel="weekly" itemValue="weekly" />
<f:selectItem itemLabel="monthly" itemValue="monthly" />
</h:selectOneMenu>
<h:panelGroup rendered="#{ReportHealth.daily}">
<h3>MENU 0</h3>
</h:panelGroup>
<h:panelGroup rendered="#{ReportHealth.weekly}">
<h3>MENU 1</h3>
</h:panelGroup>
<h:panelGroup rendered="#{ReportHealth.monthly}">
<h3>MENU 2</h3>
</h:panelGroup>
Here is the backing bean:
public class ReportHealth implements Serializable{
private static final long serialVersionUID = 1L;
private boolean weekly;
private boolean monthly;
private boolean daily;
private String menuValue;
public ReportHealth() {
weekly = false;
monthly = false;
daily = false;
}
public String getMenuValue() {
return menuValue;
}
public void setMenuValue(String menuValue) {
this.menuValue = menuValue;
}
public boolean isWeekly() {
return weekly;
}
public void setWeekly(boolean weekly) {
this.weekly = weekly;
}
public boolean isMonthly() {
return monthly;
}
public void setMonthly(boolean monthly) {
this.monthly = monthly;
}
public boolean isDaily() {
return daily;
}
public void setDaily(boolean daily) {
this.daily = daily;
}
public void typeSelectDropDownChange(ValueChangeEvent e)
{
String typeSelectVal = e.getNewValue().toString();
if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("daily"))
{
setDaily(true);
setWeekly(false);
setMonthly(false);
}
else if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("weekly"))
{
setDaily(false);
setWeekly(true);
setMonthly(false);
}
else if(typeSelectVal!=null && typeSelectVal.equalsIgnoreCase("monthly"))
{
setDaily(false);
setWeekly(false);
setMonthly(true);
}
else
{
setDaily(false);
setWeekly(false);
setMonthly(false);
}
}
}

I dont understand why you are using so complicated code for simple task.
Here is what you need
<h:form>
<h:panelGroup>
<h:outputLabel styleClass="captionOutputField" value="Select Report Type:"/>
<h:selectOneMenu id="selectedMenu" value="#{reportHealth.menuValue}">
<f:selectItem itemLabel="" itemValue="empty" />
<f:selectItem itemLabel="daily" itemValue="daily" />
<f:selectItem itemLabel="weekly" itemValue="weekly" />
<f:selectItem itemLabel="monthly" itemValue="monthly" />
<f:ajax render="#form">
</f:ajax>
</h:selectOneMenu>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'daily'}">
<h3>MENU 0</h3>
</h:panelGroup>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'weekly'}">
<h3>MENU 1</h3>
</h:panelGroup>
<h:panelGroup rendered="#{reportHealth.menuValue eq 'monthly'}">
<h3>MENU 2</h3>
</h:panelGroup>
</h:panelGroup>
</h:form>
and Bean will be
#ManagedBean
#ViewScoped
public class ReportHealth implements Serializable{
private static final long serialVersionUID = 1L;
private String menuValue;
public String getMenuValue() {
return menuValue;
}
public void setMenuValue(String menuValue) {
this.menuValue = menuValue;
}
}

I found out what was wrong with my code. Instead of putting the labels in <H3>tags. I needed to put it in <h:outputText> tag.

Related

jsf2 make datatable row editable does show inputtext fields

I am trying to edit a datatable row with JSF2. In debugging the editAction is showing the correct row, but the outputtext is not transformed into inputtext to allow editing, There seems to be a rendering problema executing the edit action. My bean is sessionscoped and when hitting one of the buttons (edit, add, delete, cancel) the method getListaNoticias is executed as many times as there are inputfields.
My code:
historial.xhtml
<h:form>
<h:dataTable styleClass="tablaHistorial"
value="#{historialBean.listaNoticias}" var="o">
<h:column>
<f:facet name="header">Fecha</f:facet>
#{o.fecha}
</h:column>
<h:column>
<f:facet name="header">Noticia</f:facet>
<h:inputTextarea value="#{o.titulo}" rendered="#{o.editable}"/>
<h:outputText value="#{o.titulo}" rendered="#{not o.editable}" />
</h:column>
<h:column>
<h:commandButton action="#{historialBean.editAction(o)}">
<f:ajax render="#form" />
</h:commandButton>
</h:column>
<h:column>
<h:commandButton action="#{historialBean.save(o)}">
<f:ajax render="#form" execute="#form" />
</h:commandButton>
</h:column>
<h:column>
<h:commandButton action="#{historialBean.cancelarAccion(o)}">
<f:ajax render="#form" />
</h:commandButton>
</h:column>
<h:column>
<h:commandButton action="#{historialBean.borrar(o)}">
<f:ajax render="#form" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
historialBean class
#ManagedBean
#SessionScoped
public class HistorialBean implements Serializable {
private static final long serialVersionUID = 1L;
public List<Noticia> listaNoticias;
public HistorialBean() {
}
public String irAConsola() {
return navigationBean.redirectToLoggedIn();
public List<Noticia> getListaNoticias() {
ConexionUtil conexion = new ConexionUtil();
listaNoticias = new ArrayList<Noticia>();
listaNoticias = conexion.prepararListaNoticiasBBDDExterna();
return listaNoticias;
}
public void setListaNoticias(List<Noticia> listaNoticias) {
this.listaNoticias = listaNoticias;
}
public void editAction(Noticia noticia) {
noticia.setEditable(true);
}
public void editar(Noticia noticia) {
ConexionUtil conexion = new ConexionUtil();
conexion.editarNoticiaBBDDExterna(noticia);
noticia.setEditable(false);
}
public void borrar(Noticia noticia) {
ConexionUtil conexion = new ConexionUtil();
conexion.deshabilitarNoticiaBBDDExterna(noticia);
}
public void cancelarAccion(Noticia noticia) {
noticia.setEditable(false);
}
}
Noticia class
public class Noticia {
private String titulo;
private String fecha;
private boolean editable;
public Noticia(String titulo,String fecha) {
super();
this.titulo = titulo;
this.fecha = fecha;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getFecha() {
return fecha;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
}
At the end I solved it putting the creation of the list in the bean constructor:
public HistorialBean() {
ConexionUtil conexion = new ConexionUtil();
listaNoticias = new ArrayList<Noticia>();
listaNoticias = conexion.prepararListaNoticiasBBDDExterna();
}
public List<Noticia> getListaNoticias() {
return listaNoticias;
}

p:selectOneMenu value still required

In my xhtml page i have two dependant selectOneMenu, with the second one being filled in an ajax call. Here's the jsf code fragment:
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel value="Dirección:" for="direccion"/>
<p:inputText id="direccion" value="#{datosInstitucion.institucion.direccion}" required="true" label="Dirección"/>
<h:outputLabel value="Departamento:" for="departamento"/>
<p:selectOneMenu id="departamento" value="#{datosInstitucion.idDepartamento}" required="true" label="Departamento">
<f:selectItem itemLabel="Seleccione el departamento" itemValue="#{null}"/>
<c:forEach items="#{datosInstitucion.departamentos}" var="departamento">
<f:selectItem itemLabel="#{departamento.nombre}" itemValue="#{departamento.id}"/>
</c:forEach>
<f:ajax render="municipio" listener="#{datosInstitucion.cargarMunicipios()}"/>
</p:selectOneMenu>
<h:outputLabel value="Municipio:" for="municipio"/>
<p:selectOneMenu id="municipio" value="#{datosInstitucion.idMunicipio}" required="true" label="Municipio">
<f:selectItem itemLabel="Seleccione el municipio" itemValue="#{null}"/>
<c:forEach items="#{datosInstitucion.municipios}" var="municipio">
<f:selectItem itemLabel="#{municipio.nombre}" itemValue="#{municipio.id}"/>
</c:forEach>
</p:selectOneMenu>
</h:panelGrid>
This fragment of code is inside a primefaces wizard component, so when the 'next' button is pressed a validation error is caused for the second selectOneMenu even when there's a value set.
What could be causing this behavior?
Relevant backing bean code:
#ManagedBean(name = "datosInstitucion")
#ViewScoped
public class DatosInstitucion implements Serializable{
#EJB
private Instituciones instituciones;
#EJB
private Parametros parametros;
#Inject
private Mensajes mensajes;
private List<Departamento> departamentos;
private List<Municipio> municipios;
private Map<Integer, Departamento> mapaDepartamentos;
private Integer idDepartamento;
private Integer idMunicipio;
private Institucion institucion;
#PostConstruct
private void inicializar(){
this.mapaDepartamentos = new HashMap<>();
this.departamentos = parametros.consultarDepartamentos();
for(Departamento departamento : departamentos){
this.mapaDepartamentos.put(departamento.getId(), departamento);
}
this.prepararInstitucion();
}
private void prepararInstitucion(){
this.institucion = new Institucion();
this.institucion.setResponsable(new Persona());
}
public Institucion getInstitucion() {
return institucion;
}
public List<Departamento> getDepartamentos(){
return departamentos;
}
public TipoIdentificacion[] getTiposIdentificacion(){
return TipoIdentificacion.deResponsables();
}
public Integer getIdDepartamento() {
return idDepartamento;
}
public void setIdDepartamento(Integer idDepartamento) {
this.idDepartamento = idDepartamento;
}
public Integer getIdMunicipio() {
return idMunicipio;
}
public void setIdMunicipio(Integer idMunicipio) {
this.idMunicipio = idMunicipio;
}
public void cargarMunicipios(){
idMunicipio = null;
if(idDepartamento != null){
this.municipios = mapaDepartamentos.get(idDepartamento).getMunicipios();
}else{
this.municipios = Collections.emptyList();
}
}
public List<Municipio> getMunicipios() {
return municipios;
}
public void confirmar(){
this.instituciones.guardar(institucion);
this.mensajes.exito("La institución ha sido registrada en el sistema");
this.prepararInstitucion();
}
}
This is because you are using JSTL <c:foreach> with JSF. The life cycle of JSTL vs JSF matters. JSTL is executed when the view is being built, while JSF is executed when the view is being rendered. The two do not work in synch with each other. In your case, you need to use <f:selectItems> instead of <c:foreach>
Replace:
<c:forEach items="#{datosInstitucion.municipios}" var="municipio">
<f:selectItem itemLabel="#{municipio.nombre}" itemValue="#{municipio.id}"/>
</c:forEach>
with:
<f:selectItems value="#{datosInstitucion.municipios}"
var="municipio" itemLabel="#{municipio.nombre}"
itemValue="#{municipio.id}"/>
For more reading, I suggest you to read the following answer

selectonemenu showen red when have date value

i have a sample selectOneMenu that have List of date and date as values but when i try to validate i have it red i will show you my sample example :
my managed bean :
#ManagedBean
#SessionScoped
public class Testbean {
#EJB
private ManageOfPlanifieLocal manageOfPlanifie;
List<Date> listdate = new ArrayList<Date>();
Date newdate;
#PostConstruct
public void initialize() {
listdate=manageOfPlanifie.retournerdatedesplanif();;
}
public String gototest2(Date date)
{
return "test2.xhtml?faces-redirect=true";
}
public List<Date> getListdate() {
return listdate;
}
public void setListdate(List<Date> listdate) {
this.listdate = listdate;
}
public Date getNewdate() {
return newdate;
}
public void setNewdate(Date newdate) {
this.newdate = newdate;
}
}
and this is my two jsf pages :
test1.xhtml
<h:outputLabel for="dateplanif" value="date de planification : " />
<p:selectOneMenu id="dateplanif" value="#{ testbean.newdate}">
<f:selectItems value="#{testbean.listdate}" var="da" itemValue="#{da}" />
</p:selectOneMenu>
<p:commandButton value="suivant" style="color:black;" action="#{testbean.gototest2(testbean.listdate)}" update="#form" />
test2.xhtml
<h2>Choix de l'equipe</h2>
<h:outputText value="Date : "/>
<h:outputText value="#{ testbean.newdate}"/>
the problem i do sample transfer of data with out converstion just simple and i get that :
do you know i have it red and i cant move to the next page ??
When you have a list of Objects, you need to convert them, so that setting the value works properly. Try the following code.
<p:selectOneMenu id="dateplanif" value="#{testbean.newdate}">
<f:selectItems value="#{testbean.listdate}" var="da" itemValue="#{da}" />
<f:convertDateTime pattern="dd-MM-yyyy" />
</p:selectOneMenu>

Avoid loading datatable each time when i make an ajax call by clicking on each row

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());
}
}

How to get dynamically rendered <h:inputText> value in back end in JSF

I am able to render dynamic but don't know how to get those dynamically created values in back end.
test.xhtml
<h:form>
Insert Your Desire Number : <h:inputText value="#{bean.number}">
<f:ajax listener="#{bean.submitAjax}" execute="#form" render="#form" event="keyup" />
</h:inputText>
<br></br>
<h:outputText value="#{bean.text}" />
<h:dataTable value="#{bean.items}" var="item">
<h:column>
<h:inputText value="#{item.value}" />
</h:column>
</h:dataTable>
<h:commandButton value="Submit" action="#{item.submit}" />
</h:form>
If I render 3 input boxes, and when I submit the button i get the last value only, Can someone guide me how can i
Bean.java
#ManagedBean(name="bean")
#SessionScoped
public class Bean {
private int number;
private List<Item> items;
private Item item;
//getter and setter are omitted
public void submitAjax(AjaxBehaviorEvent event)
{
items = new ArrayList<Item>();
for (int i = 0; i < number; i++) {
items.add(new Item());
}
}
}
Item.java
private String value;
//getter and setter are omitted
public void submit() {
System.out.println("Form Value : "+value);
}
Your submit() method is in the wrong place. You should put it on the managed bean, not on the entity.
Thus so,
<h:commandButton value="Submit" action="#{bean.submit}" />
with
public void submit() {
for (Item item : items) {
System.out.println(item.getValue());
}
}
or more formally,
#EJB
private ItemService service;
public void submit() {
service.save(items);
}

Resources