Skip to content

Instantly share code, notes, and snippets.

@Baztoune
Created January 22, 2013 11:33
Show Gist options
  • Save Baztoune/4593951 to your computer and use it in GitHub Desktop.
Save Baztoune/4593951 to your computer and use it in GitHub Desktop.
In some cases you need the options of your selectbox to be made of a code and a label, but separated by spaces so all labels are aligned. To do this you can use a monospace font, and add the right amount of spaces (rightpad). Be sure to tell JSF to not escape the labels. I also had to implement my own converter.
/**
* return a list of JSF SelectItem made of a code and a
* label, separated by spaces. All the labels are aligned
* (depending you use a monospace font)
*/
@Factory(value = "codeSelectItemList", scope = ScopeType.SESSION)
public List<SelectItem> getFixedSizeSelectItems(){
int padSize = 8;
String padChar = StringEscapeUtils.unescapeHtml("&nbsp;");
List<RefCode> refList = (List<RefCode>) refCodeDao.loadAll();
List<SelectItem> refSelectItemList = new ArrayList<SelectItem>();
for (RefCode r : refList) {
SelectItem si = new SelectItem(r, StringUtils.rightPad(r.getCode(), padSize, padChar).concat(r.getLabel()));
refSelectItemList.add(si);
}
return refSelectItemList;
}
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.GenericValidator;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
@Name("mySelectItemConverter")
@BypassInterceptors
public class MySelectItemConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
RefCodeDao refCodeDao = (RefCodeDao) Component
.getInstance("reference.codeDao");
RefCode refCode = null;
if (StringUtils.isNotBlank(value) && GenericValidator.isLong(value)) {
try {
refCode = refCodeDao.load(Long.valueOf(value));
} catch (Exception e) {
// catch any exception
throw new ConverterException("Erreur de conversion");
}
}
return refCode;
}
@Override
public String getAsString(FacesContext context, UIComponent component,
Object value) {
String valueOut = null;
if (value != null) {
valueOut = ((RefCode) value).getId().toString();
}
return valueOut;
}
}
<h:selectOneMenu value="#{code}"
converter="mySelectItemConverter"
styleClass="monospace">
<f:selectItem itemLabel="-" />
<f:selectItems
value="#{codeSelectItemList}"
itemLabelEscaped="false" noSelectionValue="" />
</h:selectOneMenu>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment