2

I need to display <p:selectManyCheckbox> items with images. I tried to display images with in <p:selectOneRadio>. It works fine. I am programmatically adding components on UI. This is my code.

answerRadio.setLayout("custom"); //answerRadio is SelectOneRadio
customPnl = (PanelGrid) app.createComponent(PanelGrid.COMPONENT_TYPE);
            customPnl.setId("pnl"+qstnCnt);
            customPnl.setColumns(3);
radioBtn = (RadioButton) app.createComponent(RadioButton.COMPONENT_TYPE);
                        radioBtn.setId("opt"+qstnAnsIndx);
                        radioBtn.setFor("ID of answerRadio");
                        radioBtn.setItemIndex(ansIndx);
                        customPnl.getChildren().add(radioBtn);

outPnl.getChildren().add(answerRadio); //outPnl is OutputPanel that include answerRadio
outPnl.getChildren().add(customPnl);

That's <p:selectOneRadio> with images.

I'd like to use <p:selectManyCheckbox> in same way. But PrimeFaces has only a <p:radioButton> for custom layoue and not a <p:checkbox> like that. How can I achieve it anyway? How can I display <p:selectManyCheckbox> items with images ?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Duk
  • 23
  • 4
  • 1
    As to declaring/creating components: there's **nothing** which is impossible in XHTML and only possible in Java. That Java is basically an unreadable mess as compared to XHTML ``/``. I strongly recommend to stop declaring/creating components in the controller and instead to it in the view, like every other sane JSF developer does. – BalusC Jan 06 '15 at 08:13
  • So what do i need to do? – Duk Jan 06 '15 at 08:19
  • Just use XHTML. That's so much more readable and maintenance friendly. – BalusC Jan 06 '15 at 08:21

1 Answers1

2

That's not possible with <p:selectManyCheckbox>. Your best bet is to just use a bunch of <p:selectBooleanCheckbox> components instead and change the model to be Map<Entity, Boolean> instead of List<Entity>. You can loop over it using <ui:repeat>.

E.g. (normal XHTML variant; I am not going to advocate the Java createComponent() equivalent):

<ui:repeat value="#{bean.entities}" var="entity">
    <p:selectBooleanCheckbox value="#{bean.selection[entity]}" />
    ... (you can put here image, label, anything)
</ui:repeat>

with

private List<Entity> entites; 
private Map<Entity, Boolean> selection;

@PostConstruct
public void init() {
    entities = service.list();
    selection = new HashMap<>(); // No need to prefill it!
}

To check which ones are selected, loop over the map in action method:

List<Entity> selectedEntities = new ArrayList<>();

for (Entry<Entity, Boolean> entry : selection.entrySet()) {
    if (entry.getValue()) {
        selectedEntities.add(entry.getKey());
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555