package javango.forms.fields;
import java.lang.annotation.Annotation;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.google.inject.Inject;
import javango.forms.fields.annotations.Choice;
import javango.forms.fields.annotations.ChoiceFieldProperties;
import javango.forms.widgets.SelectMultipleWidget;
import javango.forms.widgets.WidgetFactory;
/**
*
* @author johns
*/
public class MultipleSelectField extends AbstractMultipleChoiceField<String> {
@Inject
public MultipleSelectField(WidgetFactory widgetFactory) {
super(widgetFactory);
setWidget(SelectMultipleWidget.class);
}
@Override
public void handleAnnotation(Annotation annotation) {
if (annotation instanceof ChoiceFieldProperties) {
ChoiceFieldProperties props = (ChoiceFieldProperties)annotation;
if (getChoices() == null) {
setChoices(new LinkedHashMap<String,String>());
}
for(Choice c : props.choices()) {
getChoices().put(c.key(), c.value());
}
}
super.handleAnnotation(annotation);
}
@Override
public String[] clean(String value, Map<String, String> errors) {
return new String[]{cleanOne(value, errors)};
}
protected String cleanOne(String value, Map<String, String> errors) {
if (StringUtils.isEmpty(value)) {
if (isRequired()) {
errors.put(getName(), REQUIRED_ERROR);
}
return null;
}
return value;
}
@Override
public String[] clean(String[] values, Map errors) {
if (values == null) {
return null;
}
String[] clean = new String[values.length];
int i=0;
for(String val : values) {
String stringValue = cleanOne(val, errors);
if (!getChoices().containsKey(stringValue)) {
errors.put(this.name, "Select a valid choice. That choice is not one of the available choices.");
}
clean[i++] = stringValue;
}
return clean;
}
}