How to dynamically build a back bean edit form
Asked Answered
I

1

3

I need to build a form dynamically putting inputText field, I'm using this code:

<h:form>
    <c:forEach items="#{userBean.getFieldList()}"  var="field">
        <h:inputText value="#{userBean.getFieldValue(field.name)}" />                       
    </c:forEach> 
    <h:commandButton value="Login" action="#{userBean.loginAction}" />          
</h:form>

the var field is a metadata and not own the field value but only their attribute. So I use

#{userBean.getFieldValue(field.name)}

to get the bean field value. The code above works well if it's used only to view the page. but not on form submit because of it's not possible to setFieldvalue by field name. Is there a way to override the problem? Is there a generale way to dynamically build a back bean edit form?

Isothermal answered 10/8, 2011 at 11:45 Comment(0)
A
2

Bind it to a Map<String, Object> property and use the brace notation [] for the dynamic map key.

E.g.

private List<Field> fields; // +getter (no setter required)
private Map<String, Object> values; // +getter (no setter required)

public UserBean() {
    fields = populateItSomehow();
    values = new HashMap<String, Object>();
}

// ...

with

<h:form>
    <c:forEach items="#{userBean.fields}" var="field">
        <h:inputText value="#{userBean.values[field.name]}" />                       
    </c:forEach> 
    <h:commandButton value="Login" action="#{userBean.loginAction}" />          
</h:form>

The field name becomes the map key and the field value becomes the map value.

Adieu answered 10/8, 2011 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.