Rohit
Rohit

Reputation: 665

Spring form binding drop down object

Facing issue in spring form binding.Say i have two models Category and Product.

@Entity
@Table(name="PRODUCT")
public class Product 
{
 @Id
 @GeneratedValue
 private long productID;

 @ManyToOne
 @JoinColumn(name="categoryID")
 private Category category;

 //Getters and setters      

 }


@Entity
@Table(name = "CATEGORY")
public class Category {

    @Id
    @GeneratedValue
    private long categoryID;

    private String categoryName;
}

In controller to render add product page

@RequestMapping(value = "/productpage", method=RequestMethod.GET)
    private ModelAndView getAddProductPage(){
        ModelAndView modelAndView = new ModelAndView("add-product","product",new Product());
        Map<Category,String> categoriesMap = new HashMap<Category, String>();
        List<Category> categories = categoryService.getAllCategories();
        if(categories != null && !categories.isEmpty())
        {
            for(Category category : categories)
            {
                categoriesMap.put(category, category.getCategoryName());
            }
        }
        modelAndView.addObject("categoryList",categories);
        return modelAndView;
    }

I am able to populate the drop down values of categories in JSP page using below code :

<form:select path="category" >
<form:options items="${categoryList}"/>
</form:select>

While submitting the form i'm facing error 400 The request sent by the client was syntactically incorrect.Failed to convert property value of type 'java.lang.String' to required type 'com.example.model.Category' for property 'category'. If i view page source for each option category is assigned correctly. But not understanding why spring throwing that err.. Need help. Thanks in advance!

Upvotes: 1

Views: 2105

Answers (3)

aalmero
aalmero

Reputation: 345

<form:select path="category">
  <c:forEach items="${categoryList}" var="category">
    <form:option value="${category}">${category.categoryName}</form:option>
  </c:forEach>
</form:select> 

or

<form:select class="form-control" path="site">
    <form:option value="-1">Select...</form:option>
    <form:options items="${categoryList}" itemValue="categoryID" itemLabel="categoryName"/>                     
</form:select>  

Upvotes: 0

Rohit
Rohit

Reputation: 665

This worked for me!

<form:select path="category.categoryID" >
<form:options items="${categoryList}" itemValue="categoryID"  />
</form:select> 

Upvotes: 1

Dev-an
Dev-an

Reputation: 462

You should make the following change in your Controller's action:

for(Category category : categories)
{
    categoriesMap.put(category.geCategorytId(), category.getCategoryName());
}

and in your view change:

<form:select path="category.categoryID" >

The select drop-down will have the category name as the display text and category ID as the value.

Upvotes: 0

Related Questions