更新PropertyModel时,java Wicket表单组件失去引用
我有一个带有一些字段和下拉选项的表单。其中一个是动态填充的:当州被填充时,城市下拉列表会被更新,在这里之前都没关系
动态填充下拉列表(我使用hibernate作为ORM):
// in my form constructor
// umf is my model
umf = new Umf();
DropDownChoice stateChoice = new DropDownChoice<State>(
"states",
new PropertyModel(umf, "state"),
em.createQuery("from State e").getResultList(),
new ChoiceRenderer<State>("name")
);
DropDownChoice citiesChoice = new DropDownChoice<City>(
"cities",
new PropertyModel(umf, "city"),
new ArrayList<City>(),
new ChoiceRenderer<>("name")
);
当我试图清除表单和我的模型,让表单为其他提交做好准备时,问题发生在第一次表单提交之后(这很正常)
第一个问题是在onSubmit方法中,在数据库中持久化对象之后,我为我的模型设置了一个新对象:umf = new Umf();
,以便准备持久化一个新的umf。在此之后,组件似乎失去了umf参考
定义下拉列表状态模型的行:new PropertyModel(umf, "state")
不再有效,因为即使我在下拉列表中更改状态,umf.state
属性模型也不会更新(始终为0),因此城市下拉列表不会被填充
// right after statesChoice and citiesChoice declaration
statesChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
citiesChoice.setChoices(
em.createQuery("from City m where m.state.id = :state_id")
.setParameter("state_id", umf.getState().getId())
.getResultList()
);
target.add(cititesChoice);
}
});
是不是那个小门有用?如果组件的属性模型引用接收到一个新对象,组件将丢失其引用,需要显式重置吗
# 1 楼答案
将
new PropertyModel(umf, "state")
更改为new PropertyModel(form.getModel(), "umf.state")
。同样适用于city
您面临的问题是,一旦将
umf
传递给PropertyModel
,它就会作为自己的成员字段保存在其中。稍后,更改表单中的引用,但PropertyModel仍然指向其成员字段,即旧字段通过传递表单的模型,它变得动态——每当PropertyModel需要状态时,它都会向表单的模型请求modelObject