function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jancy MaryJancy Mary 

How to fetch the Parent's parent Id in Apex code.

Hi All,

Placement object has a lookup relationship to Account and Contact, I want to show the number of placements on each Account, however if multiple Placements are associated to the same Contact in different interval of time period which intern is associated to particular Account, then all those Placements which are associated to that Contact should be considered as 1 count under that particular Account. 

I tried writing the below apex class, but stuck in the middle. With the below code I am able to fetch the ContactID and the AccountID when a placement record is inserted, however I am unable to compare the Contact's Account with the fetched AccountID. Or if there is any alternative way to achieve this please suggest.


public class totalOfPlacementsTriggerHelper{

 public static void handleAfterInsert(List<rnm__Placement__c> placementlist)
  {
    List<Account> acc= new List<Account>();
    Set<Id> accActiveId= new Set<Id>();
    Set<Id> conId= new Set<Id>();
  
      for(rnm__Placement__c p: placementlist)
      {
        if(p.Active__c==True)
        {
        if(p.rnm__Employer__c!=null && p.rnm__Contact__c!=null)   //rnm__Employer__c is a lookup to Account
        {
        accActiveId.add(p.rnm__Employer__c);
        conId.add(p.rnm__Contact__c);
        system.debug('TESTING'+accActiveId+' '+conId);
        }
      } 
      }
}


Thanks in Advance,
Jancy Mary
sfdcsushilsfdcsushil
Hi,

Related object fields are not directly available in trigger. you will have to query them. e.g. if you want to fetch Contact's Account. You need to put all contact ids in set first, write a query against that set of contacts and fetch required fields. You can store this data in a map. 
Now again you can iterate through placement list and do required comparison. 
ArmouryArmoury

By having a junction object called Placement, technically the Account and Contact is now have capability for m:n relationship. So just want to clarify few scenarios on your business case.

Scenario 1:
Record 1 : Account1 is related to Contact1 in the year 2000
Record 2 : Account1 is related to Contact2 in the year 2000
So what is the count of Account1 should be in this case?

Scenario 2:
Record 1 : Account1 is related to Contact1 in the year 2000
Record 2 : Account1 is related to Contact1 in the year 2002
The count on Account1 should be 2 right?

Scenario 3:
Record 1 : Account1 is related to Contact1 in the year 2000
Record 2 : Account1 is related to Contact1 in the year 2002
Record 3 : Account1 is related to Contact2 in the year 2002
So what is the count of Account1 should be in this case?
Jancy MaryJancy Mary
Hi Armoury and Sushil,

Thanks for the reply, I would like my code to work in below scenarios:
Consider I have the below records.
Account Record: TestAccount1
Contact Record: TestContact1
                         TestContact2

Scenario 1:
1. If I insert a Placement1 record accoiating with TestAccount1 & TestContact1, the "Total Placements" on Account should show 1.
2. If I insert a Placement2 associating with TestAccount1 & TestContact2, the "Total Placements" on Account should now show 2.
(I want to know how many Contacts(Candidates) are been processed(Placed) for each Account, if I have for example 4 placements processed through TestContact1 for the same TestAccount1, now it should show the total placemets as 1 on Account, if I have another 2 placements processed for a different contact TestContact2 and for the same TestAccount1, now the total placemets on Account should show 2. 

If in future I insert a new Placement with TestContact1 and TestAccount2, it should still show me the count as 2. But if I insert another placement with TestContact3 and TestAccount1 the total placemets on Account should show 3 as the contact is different this time. 

I really appreciate your help, eager to resolve this with your guidance.

Thanks a lot,
Jancy Mary

 
ArmouryArmoury
Can u try the below code. Pls add/change null conditions, data types (String/Integer) and the criterias as per your requirement..
trigger ContactCount on Placement__c (after Insert, after Update) {
    
    Set<Id> accountIdSet = new Set<Id>();
    for(Placement__c placement : trigger.new) {
        accountIDSet.add(placement.account__c);
    }
    AggregateResult[] placementResult = [SELECT Contact__c, Account__c
                                         FROM Placement__c
                                         WHERE Account__c IN : accountIDSet
                                         AND Active__c = true 
                                         GROUP BY Account__c, Contact__c];
    Map<Id, Set<Id>> accountContactMap = new Map<Id,Set<ID>>();
    for(AggregateResult ar : placementResult) {
        Id accountId = (Id)ar.get('Account__c');
        Id contactId = (Id)ar.get('Contact__c');
        if (accountContactMap.get(accountId) == null) {
            accountContactMap.put(accountId, new Set<Id>());
        }
        accountContactMap.get(accountId).add(contactId);
    }
    List<Account> updateAccList = new List<Account>();
    for(Id accountId : accountIDSet) {
        String placementCount;
        if (accountContactMap.get(accountId) != null ) {
            placementCount = String.valueOf(accountContactMap.get(accountId).size());
        } else {
        	placementCount= '0';
        }
        Account acc = new Account(Id = accountId, Total_Placements__c=ContactCount);
        updateAccList.add(acc);
    }
    update updateAccList;
}


 
ArmouryArmoury
You can try this as well.. (a bit simplified approach)..
trigger ContactCount on Placement__c (after Insert, after Update) {
    
    Set<Id> accountIdSet = new Set<Id>();
    for(Placement__c placement : trigger.new) {
        accountIDSet.add(placement.account__c);
    }
    AggregateResult[] placementResult = [SELECT Count_Distinct(Contact__c) PlacementCount, Account__c
                                         FROM Placement__c
                                         WHERE Account__c IN : accountIDSet
                                         AND Active__c = true 
                                         GROUP BY Account__c];
    Map<Id, Integer> accountPlacementCountMap = new Map<Id,Integer>();
    for(AggregateResult ar : placementResult) {
        Id accountId = (Id)ar.get('Account__c');
        Integer placementCount = (Integer)ar.get('PlacementCount');
        if (accountPlacementCountMap.get(accountId) == null) {
            accountPlacementCountMap.put(accountId, placementCount);
        }
    }
    List<Account> updateAccList = new List<Account>();
    for(Id accountId : accountIDSet) {
        Integer placementCount = 0;
        if (accountPlacementCountMap.get(accountId) != null ) {
            placementCount = accountPlacementCountMap.get(accountId);
        } 
        Account acc = new Account(Id = accountId, Total_Placements__c=placementCount);
        updateAccList.add(acc);
    }
    update updateAccList;
}