Tag: JSF Java Recursively Properties

How to set recursively component properties using Java Server Faces (JSF)

Hello,

I am using a piece of code that setting disabled=true and readonly=true to all components inside of a Form, but you can use this in other situations:

In your .jspx File:

<f:view beforePhase="#{someController.makeFormReadOnly}">

In your .java File:


import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import java.lang.reflect.Method;

public void makeFormReadOnly(FacesContext facesContext, UIComponent component) {
    try {
        Method[] methods = component.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().equals("getChildren")) {
                List<UIComponent> listaComp = (List<UIComponent>)method.invoke(component);
                for (UIComponent comp : listaComp) {
                    makeFormReadOnly(facesContext, comp);
                }
            }
        }
        component.setValueExpression("readOnly", getValueExpression(facesContext, "#{true}"));
        component.setValueExpression("disabled", getValueExpression(facesContext, "#{true}"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private ValueExpression getValueExpression(FacesContext facesContext, String name) {
    Application app = facesContext.getApplication();
    ExpressionFactory elFactory = app.getExpressionFactory();
    ELContext elContext = facesContext.getELContext();
    return elFactory.createValueExpression(elContext, name, Object.class);
}