Find your content:

Search form

You are here

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(,rel.decimal_field__c); } }

The page :

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

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 !!!!

Attribution to: Rao

Possible Suggestion/Solution #1

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]}"/>

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]}"/>

Attribution to: Greg Grinberg

Possible Suggestion/Solution #2

For small sets you can just nest apex:repeat controls and render when the items are equal:

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

It's not efficient (~n^2), but it works well for small sets.

Attribution to: NSjonas

Possible Suggestion/Solution #3

You can concatenate all keys of the map to a string and then use the string to render the section where the map is used in vf page.

Attribution to: zuke
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content