I am trying to create a dynamic menu: a menu like those found on Amazon or eBay to browse categories. My first attempt is shown below:
The backing bean:
@ManagedBean
@ViewScoped
public class CategoryBackBean implements ActionListener {
private MenuModel model;
private Category category;
public CategoryBackBean() throws IOException {
category = Category.createRootCategory();
createModel();
}
private void createModel() throws IOException {
MenuModel tempModel = new DefaultMenuModel();
for(Category c : category.getChildCategories()) {
MenuItem childItem = new MenuItem();
childItem.setValue(c.getName());
childItem.addActionListener(this);
tempModel.addMenuItem(childItem);
}
this.model = tempModel;
}
public MenuModel getModel() {
return model;
}
@Override
public void processAction(ActionEvent event) throws AbortProcessingException {
try {
MenuItem item = (MenuItem) event.getSource();
String categoryName = (String) item.getValue();
for(Category c : category.getChildCategories()) {
if(c.getName().equals(categoryName)) {
category = c;
createModel();
return;
}
}
} catch (IOException ex) {
Logger.getLogger(CategoryBackBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The webpage:
<h:body>
<h:form>
<p:menubar model="#{categoryBackBean.model}" />
</h:form>
</h:body>
For starters, my design doesn’t work: the initial menu is created, but when clicking on buttons, the menu is not recreated in sub-categories.
What is the best way to tackle this general problem? I’m not looking for quick hacks to get the above code working- I’m looking for a general design for a recursive menu.
You need to update the menu after the action is completed. Given that you don’t want to hardcode the menu ID, use
@parent.An alternative, if the menu is the sole component in the form, is to just use
@form.Whether this all is the “best” way or not can’t be objectively answered. If the code does exactly the job you want in the simplest possible and least intrusive way, then it’s acceptable.