com.databasesandlife.util.wicket.OptionalSingleValueChosenDropDown Maven / Gradle / Ivy
Show all versions of java-common Show documentation
package com.databasesandlife.util.wicket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.ListMultipleChoice;
import org.apache.wicket.model.IModel;
/**
* Drop-down using "chosen" JS library, only zero or one options may be selected
*
* This is a hack. Wicket has a DropDownChoice but it always insists on
* providing a "Please choose..." text as the first entry, in case the model is
* null. We don't want that, as this is done in Javascript. HOWEVER: the
* multiple="true" means we get multiple-select which we don't want. AND: If
* there is no "" option then the "X" doesn't appear, so we allow that as a
* valid option
*
* @author This source is copyright Adrian Smith and licensed under the LGPL 3.
* @see Project on GitHub
*/
public class OptionalSingleValueChosenDropDown extends ListMultipleChoice {
protected static class EmptyStringIntroducingModel implements IModel> {
protected IModel singleStringOrNullModel;
EmptyStringIntroducingModel(IModel m) { singleStringOrNullModel = m; }
@Override public void detach() { }
@Override public List getObject() {
var value = singleStringOrNullModel.getObject();
if (value == null) value = "";
return List.of(value);
}
@Override public void setObject(List newList) {
var newValue = newList.get(0).isEmpty() ? null : newList.get(0);
singleStringOrNullModel.setObject(newValue);
}
}
public OptionalSingleValueChosenDropDown(String wicketId, IModel model, List choices) {
super(wicketId);
setDefaultModel(new EmptyStringIntroducingModel(model));
var choicesAndEmptyString = new ArrayList<>(choices);
choicesAndEmptyString.add(0, "");
setChoices(choicesAndEmptyString);
add(new Behavior() {
@Override public void onComponentTag(final Component component, final ComponentTag tag) {
tag.getAttributes().remove("multiple");
}
});
}
}