Skip to content

Instantly share code, notes, and snippets.

@kevindoran
Created February 15, 2012 08:06
Show Gist options
  • Save kevindoran/1834327 to your computer and use it in GitHub Desktop.
Save kevindoran/1834327 to your computer and use it in GitHub Desktop.
Dynamic Category Menu Model
public class CategoryMenuModel implements MenuModel, ActionListener, Serializable {
private static final long serialVersionUID = -2866930830066526910L;
protected Category category;
protected List<UIComponent> contents = new ArrayList<>();
protected static UIViewRoot uiViewRoot = new UIViewRoot();
public Category getCategory() {
return category;
}
// Creates and adds the MenuItems to the Menu
public void setCategory(Category category) throws IOException {
this.category = category;
resetContents();
for(Category childCategory : category.getChildCategories()) {
MenuItem subCategoryItem = new MenuItem();
subCategoryItem.setValue(childCategory.getName());
subCategoryItem.setId(uiViewRoot.createUniqueId());
subCategoryItem.setAjax(false);
subCategoryItem.getAttributes().put("category", childCategory);
subCategoryItem.addActionListener(this);
addMenuItem(subCategoryItem);
}
}
// Gets called when a MenuItem is clicked. The clicked MenuItem becomes the new top level MenuItem.
@Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
if(event.getSource().getClass() == MenuItem.class) {
MenuItem sourceItem = (MenuItem) event.getSource();
Category newCategory = (Category) sourceItem.getAttributes().get("category");
setCategory(newCategory);
}
}
@Override
public List<UIComponent> getContents() {
return contents;
}
@Override
public void addSubmenu(Submenu submenu) {
contents.add(submenu);
}
@Override
public void addMenuItem(MenuItem menuItem) {
contents.add(menuItem);
}
protected void resetContents() {
contents = new ArrayList<UIComponent>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment