Raj
Raj

Reputation: 29

Looping a list inside a JSTL form tag in spring

I have a class Expense which has a field expensesType of type ExpenseType list. I want to display all fields both from Expense and ExpenseType class on the view page. I used for each tag to display all fields in ExpenseType, as it is a list inside Expense class. But these fields are not being rendered on view page.

In the below code, the labels Name and Price within the for each tag are not displayed. I tried to display some value using c:out tag placing next to the foreach tag, but it is never shown which implies it is failing at c:forEach

Here is my jsp code:

    <form:form method="POST" modelAttribute="expenses" action="saveExpense">
          <div class="box-body">
                <div class="form-group col-xs-6 text-spacing">
                      <label>Expense Date</label>
                     <form:input path="date" id="expenseDate" class="form-control"/>
                     <form:errors path="date" cssClass="error" />
                    </div>
                <div class="form-group col-xs-6 text-spacing">
                  <label>Shop/Dealer Name</label>
                  <form:input path="shopName" type="text" class="form-control" placeholder="dealer name"/>
                  <form:errors path="shopName" cssClass="error" />
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <div data-role="dynamic-fields">
                                <div class="form-inline">
                                 <c:forEach items="${expenses.expensesType}" varStatus="status">
                                     <div class="form-group">
                                        <label class="sr-only" for="field-name">Name</label>
                                        <form:input path="expensesType[${status.index}].name" type="text"/>
                                    </div>
                                    <span>-</span>
                                    <div class="form-group">
                                        <label class="sr-only" for="field-value">Price</label>
                                         <form:input path="expensesType[${status.index}].price" type="text"/>
                                    </div>
                                    <button class="btn btn-danger" data-role="remove">
                                        <span class="glyphicon glyphicon-remove"></span>
                                    </button>
                                    <button class="btn btn-primary" data-role="add">
                                        <span class="glyphicon glyphicon-plus"></span>
                                    </button>
                                 </c:forEach>
                                </div>  
                            </div> 
                        </div> 
                    </div>
                </div>
            </div>
          <div class="box-footer">
            <button type="submit" class="btn btn-primary">Save</button>
             <a class="btn btn-primary" href="<c:url value='expensesList'/>"> Cancel </a>
          </div>
      </form:form>

My controller:

    @RequestMapping(value = "/expensesForm", method = RequestMethod.GET)
    public String getForm(Model model) {
        model.addAttribute("expenses", new Expenses());
        return "expensesForm";
    }

    @RequestMapping(value = "/saveExpense", method = RequestMethod.POST)
    public String saveCattleDetails(@Valid @ModelAttribute("expenses") Expenses expenses, BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            return "expensesForm";
        }
        expensesService.add(expenses);
        return "redirect:expensesList";
    }

Model classes

public class Expenses implements Serializable {

    private static final long serialVersionUID = 668608674926007321L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(name = "EXPENSES_ID", unique = true)
    private String id;

    @NotNull
    @Column(name = "DATE")
    private Date date;

    @Column(name = "SHOP_NAME")
    private String shopName;

    @Column(name = "TOTAL_EXPENSE")
    private String totalExpenses;

    @Column(name = "DESCRIPTION")
    private String description;

    @OneToMany(mappedBy = "expenses", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<ExpensesType> expensesType;

and

@Entity
@Table(name = "EXPENSES_TYPE")
public class ExpensesType implements Serializable {

    private static final long serialVersionUID = 3002107481242774411L;

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(name = "EXPENSE_TYPE_ID", unique = true)
    private String id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "EXPENSES_ID")
    private Expenses expenses;

    @Column(name = "NAME")
    private String name;

    @Column(name = "CATEGORY")
    private CategoryType category;

    @Column(name = "PRICE")
    private String price;

What could be the possible error for these fields not being shown.

Upvotes: 2

Views: 1063

Answers (1)

Kuldeep S Chauhan
Kuldeep S Chauhan

Reputation: 252

When you are adding a attribute in your model i.e

  model.addAttribute("expenses", new Expenses());

You haven't set the expensesType field of the bean Expenses, you just used new Expenses().

Instead Try initializing the field expensesType as new ArrayList(). i.e

Expenses exp = new Expenses();
exp.setExpensesType(new ArrayList());
model.addAttribute("expenses", exp);

Upvotes: 2

Related Questions