How to dynamically build a back bean edit form

不问归期 提交于 2019-12-04 15:10:54

问题


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.



来源:https://stackoverflow.com/questions/7010256/how-to-dynamically-build-a-back-bean-edit-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!