user4446735
user4446735

Reputation:

Get label of <p:selectOneMenu> when using <f:selectItems> on Map

I am trying to get the label of <p:selectOneMenu> when using <f:selectItems> on a Map.

View:

<p:selectOneMenu id="console" value="#{formBean.userRegion}" style="width:125px">
    <f:selectItems value="#{formBean.region.regions}"></f:selectItems>
</p:selectOneMenu>

Bean:

@Inject
private Region region; //where region.getRegions() is LinkedHashMap   

public void regionChanged(AjaxBehaviorEvent e) {

//it prints map element value but I need element name
            System.out.println("userRegion= " + userRegion);

        //...

    }

How can I achieve this?

Upvotes: 0

Views: 856

Answers (1)

BalusC
BalusC

Reputation: 1108632

This suggests that the model is broken. You should instead of a Map<K, V> have a List<Region> where the Region is an entity having K and V properties (and rename that backing bean currently having the class name Region).

Otherwise, just loop through the map to get the key by value.

E.g.

public static <K, V> K getKey(Map<K, V> map, V value) {
    for (Entry<K, V> entry : map.entrySet()) {
        if (entry.getValue().equals(value)) {
            return entry.getKey();
        }
    }

    return null;
}

Which you then use as

String key = getKey(region.getRegions(), userRegion);

But, again, your model is broken. Better fix the model straight away instead of introducing ugly workarounds.

Upvotes: 1

Related Questions