Saturday, 12 April 2014

How to get Contacts associated to a particular opportunity?

It will be a good practice for you to get aware of how apex and visualforce works. 

So lets get started .... Lemme create a very simple scenario for you . Say, I want to get all the contacts that are associated to an opportunity. 

remember:- Before writing any class and visualforce first try to understand the basic requirement and dnt feel shy while noting down on a piece of paper . 

So lets first try to understand how can I retrieve Contacts . What is the relation b/w contacts and opportunity. 
On every Opportunity there is account and account has many contacts associated with it. So, the idea is to first have the Account associated with the current opportunity. then get all the ids of contacts associated with it.
  

I am just going to copy the Apex class that i have written on my personal org. :-


public class ContactList {
    Id opid=ApexPages.currentPage().getParameters().get('id');
    list<opportunity> oplist = new list<opportunity>();
    set<id> acid= new set<id>();
    list<Contact> cont = new list<Contact>();
    public list<Contact> getContactss(){
        for(Account acc:[Select id , name,(select id,lastname from contacts) from Account 
                where AnkushTest__Opportunity__c= :opid])//ApexPages.currentPage().getParameters().get('id')
            { 
               system.debug('=========='+opid);
               system.debug(acc.id+'************************');
               acid.add(acc.id);
            }
        system.debug('========'+acid);
        for(contact con:[select id , name,Accountid,phone from contact where accountid in : acid]){
            cont.add(con);
            system.debug(acid);
        }
        return cont;
    }
    
    public ContactList(ApexPages.StandardController controller) {

    }





visualforce page :-


<apex:page standardController="opportunity" extensions="ContactList">
    <apex:form >
         <apex:pageBlock title="My Content">

        <apex:pageBlockTable value="{!Contactss}" var="item">
        <apex:column >
                <apex:outputLink target="_blank" value="/{!item.id}">{!item.id}</apex:outputLink>
            </apex:column>

           <apex:column value="{!item.Accountid}"/>
           <apex:column value="{!item.phone}"/>

        </apex:pageBlockTable> 

    </apex:pageBlock>
    </apex:form>
</apex:page>
               


Remenber:- You need to append id in URL of the opportunity for which you want to get contacts.
like this   
apex/ContractList/?id=006i000000HRFOw



Happy coding !!
Cheers



No comments:

Post a Comment

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...