-->

How to dynamically build a back bean edit form

2020-06-06 04:43发布

问题:

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?

回答1:

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.