I need help to render a component that will in turn make an ajax call after it has been rendered but with no success.
I have the following code which doesn't work. I don't know if I am missing something. Any help is highly appreciated.
<h:selectOneMenu id="gender" value="#{bean.gender}"
class="form-control"
valueChangeListener="#{bean.updateGenderValue}"
onchange="submit()">
<f:selectItems value="#{bean.genders}" var="gender" itemLabel="#
{gender}" itemValue="#{gender}"/>
</h:selectOneMenu>
<h:selectOneMenu value="#{bean.pregnancyStatus}"
class="form-control"
rendered="#{bean.gender eq 'Female'}">
<f:selectItems value="#{bean.options}"
var="pregnancyStatus" itemLabel="#{pregnancyStatus}"
itemValue="#{pregnancyStatus}"/>
<f:ajax listener="#{bean.updatePregancyValue}"
execute="#this" render="#this"/>
</h:selectOneMenu>
public void updateGenderValue(ValueChangeEvent event) throws IOException {
gender = (String) event.getNewValue();
}
public void updatePregancyValue(AjaxBehaviorEvent event) throws IOException {
System.out.println(":( == " + pregnancyStatus);
}
The pregnancyStatus value is never updated at all.
Did you missed the <h:form>? I copied and pasted your code in my project and
my code:
<div style="height:500px">
<h:form>
<h:selectOneMenu id="gender" value="#{bean.gender}"
class="form-control"
valueChangeListener="#{bean.updateGenderValue}"
onchange="submit()">
<f:selectItems value="#{bean.genders}" var="gender" itemLabel="#
{gender}" itemValue="#{gender}"/>
</h:selectOneMenu>
<h:selectOneMenu value="#{bean.pregnancyStatus}"
class="form-control"
rendered="#{bean.gender eq 'Female'}">
<f:selectItems value="#{bean.options}"
var="pregnancyStatus" itemLabel="#{pregnancyStatus}"
itemValue="#{pregnancyStatus}"/>
<f:ajax listener="#{bean.updatePregancyValue}"
execute="#this" render="#this"/>
</h:selectOneMenu>
lets check the console :
:( == 2
:( == 3
Bean:
#ManagedBean(name = "bean")
#ViewScoped
public class Bean {
private String pregnancyStatus;
private List<SelectItem> options;
private List<SelectItem> genders;
private String gender;
#PostConstruct
public void initBean(){
options = new ArrayList<>();
genders = new ArrayList<>();
options.add(new SelectItem("1"));
options.add(new SelectItem("2"));
options.add(new SelectItem("3"));
genders.add(new SelectItem("Male"));
genders.add(new SelectItem("Female"));
genders.add(new SelectItem("third"));
}
public String getPregnancyStatus() {
return pregnancyStatus;
}
public void setPregnancyStatus(String pregnancyStatus) {
this.pregnancyStatus = pregnancyStatus;
}
public void updateGenderValue(ValueChangeEvent event) throws IOException {
gender = (String) event.getNewValue();
}
public void updatePregancyValue(AjaxBehaviorEvent event) throws IOException {
System.out.println(":( == " + pregnancyStatus);
}
}
Related
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.
I have the following code in my facelet page:
<hc:rangeChooser1 id="range_chooser"
from="#{testBean.from}"
to="#{testBean.to}"
listener="#{testBean.update}"
text="#{testBean.text}">
<f:ajax event="rangeSelected"
execute="#this"
listener="#{testBean.update}"
render=":form:growl range_chooser"/>
</hc:rangeChooser1>
This is my composite component:
<ui:component xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.org/ui">
<cc:interface componentType="rangeChooser">
<!-- Define component attributes here -->
<cc:clientBehavior name="rangeSelected" event="change" targets="hiddenValue"/>
<cc:attribute name="from" type="java.util.Calendar"/>
<cc:attribute name="to" type="java.util.Calendar"/>
<cc:attribute name="text" type="java.lang.String"/>
</cc:interface>
<cc:implementation>
<div id="#{cc.clientId}">
...
<p:inputText id="hiddenValue" value="#{cc.attrs.text}"/>
...
</div>
</cc:implementation>
</ui:component>
How do I pass attributes from, to and text from composite component to backing bean? I mean inject these values in backing component, and not through
<p:inputText id="hiddenValue" value="#{cc.attrs.text}"/>
Update: there's more correct definition what do I need: Be able to mutate objects which I pass from the backing bean to the composite component inside a backing component of the composite component. So when I perform process or execute my composite component I get the updated values.
This is my backing component:
#FacesComponent("rangeChooser")
public class RangeChooser extends UIInput implements NamingContainer {
private String text;
private Calendar from;
private Calendar to;
#Override
public void encodeBegin(FacesContext context) throws IOException{
super.encodeBegin(context);
}
public String getText() {
String text = (String)getStateHelper().get(PropertyKeys.text);
return text;
}
public void setText(String text) {
getStateHelper().put(PropertyKeys.text, text);
}
/*
same getters and setters for Calendar objects, from and to
*/
}
I just can't realize how do I move on? In general I need to take a value from <p:inputText id="hiddenValue" value="#{cc.attrs.text}"/> and convert it to two Calendars object from and to.
It will be great if somebody can point me toward right direction from here. I know that I need to use getAttributes().put(key,value) but don't know where to put this code. Thank you in advance.
Based on your comments this is what you expect.
Note that even if this implementation works, it is conceptually incorrect!
You are considering from and to as INPUTS (not input components, but input values) and text as OUTPUT. This is not the way JSF is intended to work!
However, here it is
<cc:interface componentType="rangeComponent">
<cc:attribute name="from" />
<cc:attribute name="to" />
<cc:clientBehavior name="rangeSelected" event="dateSelect" targets="from to"/>
</cc:interface>
<cc:implementation>
<div id="#{cc.clientId}">
<p:calendar id="from" value="#{cc.attrs.from}"/>
<p:calendar id="to" value="#{cc.attrs.to}"/>
</div>
</cc:implementation>
used in page:
<h:form>
<e:inputRange from="#{rangeBean.from}" to="#{rangeBean.to}" text="#{rangeBean.text}">
<p:ajax event="rangeSelected" process="#namingcontainer" update="#form:output" listener="#{rangeBean.onChange}" />
</e:inputRange>
<h:panelGrid id="output" columns="1">
<h:outputText value="#{rangeBean.from}"/>
<h:outputText value="#{rangeBean.to}"/>
<h:outputText value="#{rangeBean.text}"/>
</h:panelGrid>
</h:form>
with this backing component:
#FacesComponent("rangeComponent")
public class RangeComponent extends UINamingContainer
{
#Override
public void processUpdates(FacesContext context)
{
Objects.requireNonNull(context);
if(!isRendered())
{
return;
}
super.processUpdates(context);
try
{
Date from = (Date) getValueExpression("from").getValue(context.getELContext());
Date to = (Date) getValueExpression("to").getValue(context.getELContext());
ValueExpression ve = getValueExpression("text");
if(ve != null)
{
ve.setValue(context.getELContext(), from + " - " + to);
}
}
catch(RuntimeException e)
{
context.renderResponse();
throw e;
}
}
}
with this backing bean:
#ManagedBean
#ViewScoped
public class RangeBean implements Serializable
{
private static final long serialVersionUID = 1L;
private Date from = new Date(1000000000);
private Date to = new Date(2000000000);
private String text = "range not set";
public void onChange(SelectEvent event)
{
Messages.addGlobalInfo("[{0}] changed: [{1}]", event.getComponent().getId(), event.getObject());
}
// getters/setters
}
I rewrote the code using BalusC tecnique (and without PrimeFaces):
the form:
<h:form>
<e:inputRange value="#{rangeBean.range}">
<p:ajax event="change" process="#namingcontainer" update="#form:output"
listener="#{rangeBean.onChange}" />
</e:inputRange>
<h:panelGrid id="output" columns="1">
<h:outputText value="#{rangeBean.range}" />
</h:panelGrid>
</h:form>
the composite:
<cc:interface componentType="rangeComponent">
<cc:attribute name="value" />
<cc:clientBehavior name="change" event="change" targets="from to"/>
</cc:interface>
<cc:implementation>
<div id="#{cc.clientId}">
<h:inputText id="from" binding="#{cc.from}">
<f:convertDateTime type="date" pattern="dd/MM/yyyy" />
</h:inputText>
<h:inputText id="to" binding="#{cc.to}">
<f:convertDateTime type="date" pattern="dd/MM/yyyy" />
</h:inputText>
</div>
</cc:implementation>
the backing component:
#FacesComponent("rangeComponent")
public class RangeComponent extends UIInput implements NamingContainer
{
private UIInput from;
private UIInput to;
#Override
public String getFamily()
{
return UINamingContainer.COMPONENT_FAMILY;
}
#Override
public void encodeBegin(FacesContext context) throws IOException
{
String value = (String) getValue();
if(value != null)
{
String fromString = StringUtils.substringBefore(value, "-");
String toString = StringUtils.substringAfter(value, "-");
try
{
from.setValue(from.getConverter().getAsObject(context, from, fromString));
}
catch(Exception e)
{
from.setValue(new Date());
}
try
{
to.setValue(to.getConverter().getAsObject(context, to, toString));
}
catch(Exception e)
{
to.setValue(new Date());
}
}
super.encodeBegin(context);
}
#Override
public Object getSubmittedValue()
{
return (from.isLocalValueSet() ? from.getValue() : from.getSubmittedValue()) + "-" + (to.isLocalValueSet() ? to.getValue() : to.getSubmittedValue());
}
#Override
protected Object getConvertedValue(FacesContext context, Object submittedValue)
{
return from.getSubmittedValue() + "-" + to.getSubmittedValue();
}
public UIInput getFrom()
{
return from;
}
public void setFrom(UIInput from)
{
this.from = from;
}
public UIInput getTo()
{
return to;
}
public void setTo(UIInput to)
{
this.to = to;
}
}
and the managed bean:
#ManagedBean
#ViewScoped
public class RangeBean implements Serializable
{
private static final long serialVersionUID = 1L;
private String range = "01/01/2015-31/12/2015";
public void onChange(AjaxBehaviorEvent event)
{
Messages.addGlobalInfo("[{0}] changed: [{1}]", event.getComponent().getId(), event.getBehavior());
}
public String getRange()
{
return range;
}
public void setRange(String range)
{
this.range = range;
}
}
Note that managed bean only retains range property for get/set. From and to are gone, the backing component derives and rebuilds them itself.
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
Form field rendering is depending on selected item in selectOneMenu.
Page:
<h:body>
<f:view>
<h:form>
<h:panelGrid>
<p:inputText value="#{user.username}"/>
<p:selectOneMenu value="#{user.moreInputs}"
required="true">
<p:ajax event="change"
update="moreInputGrid"/>
<f:selectItem itemLabel="" itemValue=""/>
<f:selectItems value="#{user.selectItems}"/>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid id="moreInputGrid">
<p:inputText rendered="#{user.renderMoreInputs}"
value="#{user.name}"/>
</h:panelGrid>
<p:commandButton action="#{user.register}"
value="Register user"/>
</h:form>
</f:view>
</h:body>
Backing bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
#ManagedBean
#ViewScoped
public class User {
private String username;
private MoreInputs moreInputs;
private String name;
public enum MoreInputs {
YES,
NO
}
public boolean isRenderMoreInputs() {
return (moreInputs == MoreInputs.YES);
}
public SelectItem[] getSelectItems() {
SelectItem[] items = new SelectItem[2];
items[0] = new SelectItem(
MoreInputs.YES,
"yes");
items[1] = new SelectItem(
MoreInputs.NO,
"no");
return items;
}
public String register() {
return null;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public MoreInputs getMoreInputs() {
return moreInputs;
}
public void setMoreInputs(MoreInputs moreInputs) {
this.moreInputs = moreInputs;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Issue arrises if the client does page refresh after choosing an item causing form fields to render. Such form fields will not be rendered on page refresh, although they should. Plus, if client then tries to submit form, validation is skipped for those hidden fields and form is successfully processed.
Am I doing something wrong? Is there an elegant solution?
it seems as if it is not possible to disable items in a SelectOneMenu from PrimeFaces (3.3) when using the custom content (as shown at http://www.primefaces.org/showcase-labs/ui/selectOneMenu.jsf).
The testcase is simple, just take the following:
<h:form>
<p:selectOneMenu value="#{testBean.selected}">
<f:selectItems value="#{testBean.options}" var="t"
itemLabel="#{t.label}" itemValue="#{t}"
itemDisabled="#{t.value % 2 == 0 ? 'true' : 'false'}" />
</p:selectOneMenu>
<p:selectOneMenu value="#{testBean.selected}" var="x">
<f:selectItems value="#{testBean.options}" var="t"
itemLabel="#{t.label}" itemValue="#{t}"
itemDisabled="#{t.value % 2 == 0 ? 'true' : 'false'}" />
<p:column>
#{x.label} -- #{x.label}
</p:column>
</p:selectOneMenu>
</h:form>
and the following Java files:
Bean:
#Named
public class TestBean {
private TestObject selected;
// getter/setter
public List<TestObject> getOptions() {
return Arrays.asList(new TestObject("1"), new TestObject("2")); }
}
Object:
public class TestObject {
private Integer value;
// getter/setter
public TestObject() {}
public TestObject(String s) {
this.setLabel(s);
}
public String getLabel() {return "label: " + value;}
public void setLabel(String l) {this.value = new Integer(l);}
}
The first dropdown works fine, the second one doesn't. Any idea on how to solve that?