0

I have two DropDownChoice component of category1 and category2. I want change the list of category2 when changing the selected value of category1. But the changed value of category1 always keep the init value when the method of category1.getModelObject() invoked.

private void addCategoryChoice(Form form) {
    List<Category1> category1List = category1Impl.listProduct();

    ChoiceRenderer renderer1=new  ChoiceRenderer<Category1>() {
        @Override
        public Object getDisplayValue(Category1 value) {
            return value.getName();
        }
    };
    DropDownChoice<Category1> category1 = new DropDownChoice<Category1>("category1",
          new Model<Category1>(category1List.get(1)) , category1List,renderer1);

    category2List = category2Imple.listByCategory1Id(category1.getModelObject().getId());
    ChoiceRenderer renderer2=new  ChoiceRenderer<Category2>() {
        @Override
        public Object getDisplayValue(Category2 value) {
            return value.getName();
        }
    };
    DropDownChoice<Category2> category2 = new DropDownChoice("category2",category2List,renderer2);
    form.add(category2);

    category1.add(new AjaxEventBehavior("change") {
        @Override
        protected void onEvent(AjaxRequestTarget target) {
            category2List.clear();

            int id=category1.getModelObject().getId();
            category2List.addAll(category2Imple.listByCategory1Id(Integer.valueOf(id)));
            category2.setChoices(category2List);
        }
    });
    form.add(category1);
}

1 Answers1

3

AjaxEventBehavior doesn't update component model. You should use OnChangeAjaxBehavior instead.

Andrea Del Bene
  • 2,521
  • 1
  • 15
  • 20
  • The problem is fixed. Thanks! – firefly Apr 08 '20 at 02:42
  • I would think this would rather be done with a simple AjaxFormComponentUpdatingBehavior on the "change" event. Any specific reason you picket OnChangeAjaxBehavior? – OH GOD SPIDERS Apr 08 '20 at 11:29
  • @OHGODSPIDERS OnChangeAjaxBehavior is a smarter version of AjaxFormComponentUpdatingBehavior. It uses both `change` and `input` for TextField and TextArea. – martin-g Apr 08 '20 at 21:27