How to handle maps with no key match

I am having a map and want to expose it in the VF page and I did something like below

list<related_object__c> related_object_list =[select decimal_field__c from related_object__c limit 1];
    Map<id,decimal> map_string_id = new map <id,string>();
    for(opportunity o: [select id from opportunity where account!= null]{
for(related_object__c rel: related_object_list){
    map_string_id.put(opp.id,rel.decimal_field__c); } }

The page :

<apex:page standardcontroller="opportunity">
<apex:form>
<apex:repeat value="{!opportunity}" var="opp">
<apex:outputtext value="{!map_string_id[opp]}"/>
</apex:repeat>
</apex:form>
</apex:page>

The problem is that the map may or may not contain the opportunityID based my query in the controller and gives me

Map key 006.... not found in map

Is there a way to check in the VF page if the map containsKey ?
I want to see if there is any way I can do something like :

<apex:outputtext value="{!map_string_id[opp]}" rendered="**{!map_string_id.containsKey(opp)}**/>

Is this possible !!!!

Answer

It is not possible to check whether a Map in your controller has a key in it from your VF page in a dynamic fashion in the way you are doing. Your best bet is to either

change your repeat to iterate over the keys of the map:

<apex:repeat value="{!map_string_id.keys}" var="key">
<apex:outputtext value="{!map_string_id[key]}"/>
</apex:repeat>

create a wrapper class that checks if an opportunity is in the map:

public class oppWrapper
{
    public Opportunity opp {get; set;}
    public Boolean isInMap(){return map_string_id.containskey(opp.ID);}
} 

and the visualforce:

<apex:repeat value="{!oppWrappers}" var="wrapper">
<!--some other fields from the opportunity-->
<apex:outputtext rendered="{!wrapper.isInMap}" value="{!map_string_id[wrapper.opp]}"/>
</apex:repeat>

Attribution
Source : Link , Question Author : Rao , Answer Author : Greg Grinberg

Leave a Comment