reidestis
reidestis

Reputation: 313

How to show image on selected item of p:selectOneMenu

I'm trying to implement an advanced selectOneMenu (PrimeFaces) to choose a locale based on its flag icon. The icons are shown in the list but not for the selected item (the same happens on showcase). How could I do this?

<p:selectOneMenu id="mySOMId" value="#{localeBean.locale}" var="mySOMVar" converter="#{localeConverter}" >
    <f:selectItems 
        value="#{myBean.locales}" 
        var="localeSIVar"
        itemLabel="#{localeSIVar.language}" 
        itemValue="#{localeSIVar}" />
    <p:column style="text-align: center;" >
        <h:graphicImage library="default" height="20" name="img/#{mySOMVar.language}.svg" />
    </p:column>
</p:selectOneMenu>

I can see that f:selectItems has an itemLabelEscaped attribute, which I could use to output <img> tag in itemLabel, but I don't know what I would put on its src.

Thanks

Upvotes: 2

Views: 1329

Answers (1)

BalusC
BalusC

Reputation: 1108642

You can use the #{resource['library:name']} syntax to print an URL for the resource, as indicated in How to reference CSS / JS / image resource in Facelets template?

So, given that you actually wanted to use a

<h:graphicImage library="default" height="20" name="img/#{localeSIVar.language}.svg" />

within the itemLabel, and that itemLabelEscaped attribute of <f:selectItems> is set to true, then you can use the following syntax as value of itemLabel:

itemLabel="&lt;img height='20' src='#{resource['default:img/' += localeSIVar.language += '.svg']}' /&gt;"

Notes:

  • You can only use plain HTML there, not JSF components.
  • For improved readability, better use single quotes as attribute value separators within the plain HTML which is in turn declared as an attribute surrounded by double quotes. You can of course also use &quot; instead of these single quotes.
  • The single quotes continue to work fine in EL expression as shown above, no need for re-escaping. You can even use double quotes within the EL expression, but syntax highlighting in code editors is prone to fail here, potentially causing unnecessary confusion.
  • The += operator is new since EL 3.0; in case you're still using an older EL version, head to How to concatenate a String in EL? for alternate ways to concatenate a string in EL (and then reusing it as a variable).

Upvotes: 5

Related Questions