Duk
Duk

Reputation: 23

How to display items with image in p:selectManyCheckbox

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 ?

Upvotes: 2

Views: 1489

Answers (1)

BalusC
BalusC

Reputation: 1108642

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());
    }
}

Upvotes: 2

Related Questions