PDA

View Full Version : form:select why doesn't work



cclafuente
Sep 28th, 2007, 06:41 AM
I'm using spring and hibernate annotations, i try all the next sentences to set a role to a user:

1. <form:select path="role" items="${roles}" />

2. <form:select path="role.id" items="${roles}" itemValue="id" itemLabel="authority"/>

<form:select path="role" items="${roles}" itemValue="id" itemLabel="authority"/>

<form:select path="role">
<form:options items="${rolesLV}" itemValue="id" itemLabel="authority"/>
</form:select>

<form:select path="role.id">
<form:options items="${roles}" itemValue="id" itemLabel="authority"/>
</form:select>

1. I think that the correct was the first sentence, the most simple, but in this case, the exception was something like i was trying to convert a string in a object Role, and it was no correct.

2. In the second sentence, spring tried to change in the table Role, the id, and in the table user too, but i don't want to change nothing in the table role, i only want to change in the table users, the id of his role, the exception was:
identifier of an instance of com....Role was altered from 1 to 2; nested exception is org.hibernate.HibernateException...

In hibernate annotations, here is my code:

Role:
@Entity
@Table(name="roles")
public class Role {...
@Id @Column(name="role_id")
public String getId() {
return id;
}
.....


User:
@Entity...
.....
@ManyToOne
@JoinColumn(name="role_id")
public Role getRole() {
return role;
}

Why is trying to change the role.id in any other place that in the user.role.id?

Jörg Heinicke
Sep 29th, 2007, 09:22 PM
The best one is


<form:select path="role" items="${roles}" itemLabel="authority"/>

in conjunction with a PropertyEditor.

Joerg

cclafuente
Oct 1st, 2007, 03:42 AM
I make a property editor:

public class RolePropertyEditor extends PropertyEditorSupport{
private Manager manager;

/**
* @return the manager
*/
public Manager getManager() {
return manager;
}

public RolePropertyEditor(Manager manager){
setManager(manager);
}

/**
* @param manager the manager to set
*/
public void setManager(Manager manager) {
this.manager = manager;
}

public String getAsText(){
Role role = (Role) getValue();
return role.getId();
}

public void setAsText(String roleId){
Role role = (Role) manager.get(Role.class, roleId);
super.setValue(role);
}

}


I set this property editor on the initBinder method of the controller:

super.initBinder(request, binder);
//to use property editors
binder.registerCustomEditor(Role.class, "role", new RolePropertyEditor(manager));

I put in the jsp:

<form:select path="role" items="${roles}" itemLabel="authority"/>

and everything works correctly.
Very thanks.

Jörg Heinicke
Oct 29th, 2007, 10:35 PM
Usually the reason is a new ModelAndView() somewhere in the controller's code without including errors.getModel() passed as model. This wipes out the custom property editor again.

Joerg