Here is my problem, I have a required DropDownChoices. But in my list of choices, I have one item with an empty/null code that I consider as a valid answer. I can make it accept (solution below), but i can't have it initialize with the correct value.
Here is the idea, I have this object : Item { String code; String label}
and the next code :
List<Item> choices = new ArrayList<Item>();
choices.add(new Item("ok","labelOk"));
choices.add(new Item("","labelEmpty"));
ChoiceRenderer<Item> renderer = new ChoiceRenderer<Item>("label", "code");
DropDownChoice<Item> s = new DropDownChoice<Item>("id", Model.of(new Item("","labelEmpty")), choices, renderer);
s.setRequired(true);
With just that, the second choices is not accepted. So I created a custom renderer to replace my null value with none :
public class ItemChoiceRenderer extends ChoiceRenderer<Item> {
public TListItemChoiceRenderer() {super("label", "code");}
@Override
public String getIdValue(Item object, int index) {
if (object != null && StringUtils.isNullOrEmpty(object.getCode())) {
return "none";
}
return super.getIdValue(object, index);
}
}
With that, I can select the second choice. But the DropDownChoices does not initialise on the correct value, it's select "Choose one" at the start.
It looks like the component does not use the renderer to select it's field, but I can not see why, and how to correct this.
Never mind, I found my problem, the model for the DropDownChoices was not initialized.
I let the question since it shows the solution for my problem, it might interest somebody.