How to reference a map’s keySet() and individual map elements within Visualforce? Get ‘Unknown function’ error

I have a map exposed to my visualforce page and I want to loop over it and display key and value

controller:

public Map<String,String> myMap { get; set; }

//init myMap 

page:

 <apex:repeat value="{!myMap.keySet() }" var="fieldKey">
    key: {!fieldKey }
    value: {!myMap.get(fieldKey ) }
 </apex:repeat>

but it gives the error Error: Unknown function myMap.keySet. Check spelling

Answer

The Visualforce for this situation is this:

<apex:repeat value="{!myMap}" var="fieldKey">
    key: {!fieldKey }
    value: {!myMap[fieldKey]}
</apex:repeat>

because the map key is automatically used by the apex:repeat and square brackets are the expression language way of looking up a value in a map.

PS

Most of the time the lack of ordering of the map keys isn’t a good thing; iterating over a separate controller property that contains a sorted list of the key values instead is a way to address that:

public List<String> orderedKeys {
    get {
        List<String> keys = new List<String>(myMap.keySet());
        keys.sort();
        return keys;
    }
}

PPS

See this answer for some examples of how the ordering of the keys is now more predictable.

Attribution
Source : Link , Question Author : vishesh , Answer Author : Community

Leave a Comment