^ Click Here

Saturday, January 28, 2012

Showing Opportunities for each Contact (parent - child) through Map without using Wrapper Class

We can show map from controller on the visualforce page, We also can put one map inside another map or in other words nested map.

With the help of these two factors, I successfully showed the contact and corresponding opportunities without using the wrapper classes. Though it put some restriction however for
the purpose of showing all the opportunities corresponding to each Contact (or any parent - child relationship) it works fine.

The process is simple -
 -I created a map of Contact as key and another map of Opportunity with id as value say A.
 -I used a query which brings all the opportunities for Contacts.
 -Now in a loop get the list of opportunities for each Contact.
 -After checking if there are Opportunities put those Opportunities in a map with id say B.
 -And lastly the Contact and the map B was put into map A.



Visualforce Page :-

 <apex:page controller="MapClass" action="{!getValues}">
<apex:pageblock >
<apex:pageBlockTable value="{!checkMap}" var="con">
    <apex:column value="{!con.Name}"/>
    <apex:column headerValue="Opportunities">
        <apex:dataList value="{!checkMap[con]}" var="opp">
        <apex:outputField value="{!checkMap[con][opp].Name}"/>
        </apex:dataList>
    </apex:column>
    <apex:column value="{!con.Account.Name}"/>
    <apex:column value="{!con.createddate}"/>
   
</apex:pageBlockTable>
</apex:pageblock>
</apex:page>



Apex Class :-

public class MapClass{
  public transient Map<Contact,Map<id,Opportunity>> checkMap{get; set;}
  public void getValues(){
  checkMap  = new Map<Contact,Map<id,Opportunity>>();
  for(Contact s : Database.query('select id, name, Account.name, owner.Name,    createddate, (select id, name from Opportunities) from Contact')){
      List<Opportunity> opLi = s.getSobjects('Opportunities');
      map<id,Opportunity> opMap = new map<id,Opportunity>();
      if(opLi != null){
      for(Opportunity op: opLi){
      opMap.put(op.id,op);   
      }
      }
      checkMap.put(s,opMap);
  }   
}
}

 Last but not the least you can stretch this concept to look what else can be done. feel free to add on it.



1 comment:

  1. Perfect! These articles are written by a very large, they are lot of exactly rich contents and information. They help me there.





    ReplyDelete