Saturday, October 6, 2012

JSF: setting EL expression programmatically

Issue
Create a JSF component programmatically and setting a property dynamically (eg disabled, visible, etc).

Solution
Java Server Faces provides an expression language (JSF EL)  used in web application pages to access the JavaBeans components in the page. It is possible to set it programmatically using a javax.el.ValueExpression, an abstract class that provides the API for the Unified Expression Language.

the next method provide to create a ValueExpression that represent  an EL-Expression using the ElContext.


    public static ValueExpression createValueExpression(String expression) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application app = facesContext.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        ValueExpression valueExp =
              elFactory.createValueExpression(elContext,
                                              expression,
                                              Object.class);
        return valueExp;
    }

Follows an example of usage with an ADF Faces Component: RichSelectOneChoice.

ValueExpression ve = Utils.createValueExpression("#{myRequestBean.property}");
RichSelectOneChoice rsoc= new RichSelectOneChoice ();
String name = RichSelectOneChoice.READ_ONLY_KEY.getName();
rsoc.setValueExpression(name, ve);

Every rich componet has PropertyKey Field that represents the component properties. In this case the field is used to get the name of the READ_ONLY_KEY.


1 comment:

  1. You saved my life. Thank you so much !

    ReplyDelete