使用JSF表单创建一个包含其他对象列表的对象

时间:2015-03-05 08:28:33

标签: jsf jsf-2

我正在使用GlassF 4的JSF 2.我想创建一个对象集合作为其字段之一的对象。搜索时,我只能找到在JSF表单中显示集合字段的方法。在这里我想要相反:允许用户在创建父对象时填充此集合。简化示例如下:

父对象:帐户

public class Account {
    private String accountName;
    private List<Order> orderList = new ArrayList<Order>();

    public String save() {
        System.out.println(accountName);
        System.out.println(orderList);
        return "";
    }

    // Constructors, getters and setters below.

}

子对象:订单

public class Order {
    private String orderName;
    private Integer orderCost;

    // Constructors, getters and setters below.

}

JSF Page Body

表格的想法来自BalusC的回答here

<h:body>
  <h1>Create Account</h1>
  <h:form>
    <h:panelGrid>
      Account Name: 
      <h:inputText value="#{account.accountName}" />

      <ui:repeat value="#{account.orderList}" varStatus="loop">
        Order Name:
        <h:inputText value="#{account.orderList[loop.index]}" />
        Order Cost:
        <h:inputText value="#{account.orderList[loop.index]}" />
      </ui:repeat>

    </h:panelGrid>
    <h:commandButton action="#{account.save}" value="Create" />
  </h:form>
</h:body>

我遇到了一些问题:

  • 我无法显示一定数量的订单。 (例如:每个新帐户最多5个)。仅当List已有某些对象时,才会显示输入字段。这是有道理的,但我想向用户提供他们可以填写的X空白行。
  • 我无法一次向用户公开orderName和orderCost字段。
  • 稍后我想添加一个commandButton,在UI中添加另一行inputText字段,这样用户就可以根据需要向帐户添加多个订单。

任何帮助非常感谢。很高兴回答我错过的任何问题。谢谢!


在BalusC的帮助下,我做了以下更改,现在我有了我想要的行为:

// Prop up the array so the desired number of fields appears in the UI
@PostConstruct
public void prepare() {
    orderList.add(new Order());
    orderList.add(new Order());
    orderList.add(new Order());
}

遍历空Order对象列表。没有数据被禁用,因为Order对象中的所有字段值都为空。此外,由于我在@PostConstruct中创建了对象,因此用户的更改可以轻松保存在提交中。

  <ui:repeat value="#{account.orderList}" var="order">
    Order Name:
    <h:inputText value="#{order.orderName}" />
    Order Cost:
    <h:inputText value="#{order.orderCost}" /><br/>
  </ui:repeat>

1 个答案:

答案 0 :(得分:0)

关于准备固定数量的商品和添加新商品,只需在列表中添加新商品。

orders.add(new Order());

@PostConstruct中执行此操作以准备页面加载项目,并在“添加”按钮中执行相同操作。

至于访问属性,你不需要varStatus / index技巧,因为你有可变对象的集合,而不是不可变对象的集合(你找到的问题是所有关于)。

<ui:repeat value="#{bean.orders}" var="order">
    <h:inputText value="#{order.name}" />
    <h:inputText value="#{order.cost}" />
</ui:repeat>

如果你真的坚持,你可以做#{bean.orders[loop.index].name},但如上所述,这是不必要的。