Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save many objects in a spring <form:form>

@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{      
    ....        
    @OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
    private Set<VoceMenu> voceMenuList; 

    public Set<VoceMenu> getVoceMenuList() {
        return voceMenuList;
    }

    public void setVoceMenuList(Set<VoceMenu> voceMenuList) {
        this.voceMenuList = voceMenuList;
    }
    .....   
}

I print a form to edit the menu, and its relative VoceMenu objects, this way:

<form:form action="editMenu" method="post" commandName="menu"> 
     Menu id<form:input path="id" maxlength="11"/><br/>       
     ...... 
    <c:forEach items="${menu.voceMenuList}" varStatus="counter">            
        <form:input path="voceMenuList[${counter.index}].id" maxlength="11"/>
             .....
    </c:forEach>
    <input type="submit">
</form:form>

But, when I try to save the object Menu, I get this error:

Invalid property 'voceMenuList[0]' of bean class [com.springgestioneerrori.model.Menu]: Cannot get element with index 0 from Set of size 0, accessed using property path 'voceMenuList[0]'

like image 940
MDP Avatar asked Feb 13 '15 11:02

MDP


1 Answers

The elements of a Set cannot be accessed by index. You will need to add methods which return a List wrapping your set.

@Component
@Entity
@Table(name="menu")
@Configurable
public class Menu implements Serializable{      
    ....        
    @OneToMany(mappedBy="menu", fetch=FetchType.EAGER)
    private Set<VoceMenu> voceMenus; 

    public Set<VoceMenu> getVoceMenus() {
        return voceMenus;
    }

    public void setVoceMenus(Set<VoceMenu> voceMenus) {
        this.voceMenus = voceMenus;
    }

    //bind to this
    public List<VoceMenu> getVoceMenusAsList(){
        return new ArrayList<VoceMenu>(voceMenus);
    }
    .....   
}

JSP:

<form:form action="editMenu" method="post" commandName="menu"> 
     Menu id<form:input path="id" maxlength="11"/><br/>       
     ...... 
    <c:forEach items="${menu.voceMenusAsList}" varStatus="counter">            
        <form:input path="voceMenusAsList[${counter.index}].id" maxlength="11"/>
             .....
    </c:forEach>
    <input type="submit">
</form:form>
like image 75
Alan Hay Avatar answered Nov 11 '22 22:11

Alan Hay