0

我有一个包含一些字段和 DropdownChoices 的表单。其中之一是动态填充的:当 State 被填充时,City 下拉列表会更新,直到这里都可以。

动态填充下拉列表(我使用休眠作为 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.statePropertyModel 也没有更新(始终为 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);
    }
});

像那样 Wicket 有效吗?如果组件的属性模型引用接收到一个新对象,组件会丢失它的引用并需要显式重置?

4

2 回答 2

4

更改new PropertyModel(umf, "state")new PropertyModel(form.getModel(), "umf.state")。对city.

您面临的问题是,一旦您传递umfPropertyModel它,它就会作为自己的成员字段保存在其中。稍后您更改了 Form 中的引用,但 PropertyModel 仍然指向其成员字段,即旧的。

通过传递表单的模型,它变得动态 - 每次 PropertyModel 需要状态时,它都会向表单的模型询问其模型对象。

于 2018-01-26T07:19:30.497 回答
0

找到了解决方案。我开始使用 CompoundPropertyModel 的形式:

umf = new Umf();
CompoundPropertyModel model = new CompoundPropertyModel(umf);
setDefaultModel(model);

然后组件模型引用它:

nameModel = new RequiredTextField("name", model.bind("name"));

DropDownChoice statesChoice = new DropDownChoice<State>(
    "states",
    new PropertyModel(getModel(), "state"),
    em.createQuery("from Estado e").getResultList(),
    new ChoiceRenderer<State>("name")
);
// and so on

提交后(onSubmit 方法):

umf = new Umf();

这样组件就不会丢失表单的引用。

于 2018-01-27T00:47:16.797 回答