Wednesday, 23 December 2020

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requirement to implement the same logic for lookup relationship then you have to think of an alternative way to cater to the requirement, there can be multiple ways to implement but in this blog, we will use a trigger to implement roll-up summary field logic. So before wasting any time, let's get started.😊 Read till the end to know the bonus tip.



Use Case Example :

There are two objects one is Account and another object is Contact, as you all know Account is the parent object and Contact is the child object and they share the lookup relationship between them.
.
There are  MaxSalary__c and MinSalary__c  custom fields on Account Object.MaxSalary__c field should be updated with a value that is the maximum of all the salaries(salary__c) of its related contacts and MinSalary__c  field should be updated with the value that is the minimum of all the salaries(salary__c) of its related contacts list. So in short the highest and lowest salary amount among all the contacts should be updated on its respective Account.


Solutions :

Before diving directly into code, identify the below points from the given requirement scenario.

1.Object on which Trigger is fired.
2.Which Trigger Events should be used and Why?
3.Objects, fields, and conditions on which DML operations need to be performed.



The trigger has to be written on the Contact object and as per the requirement we are performing calculations on the trigger after the user submits or update or delete or undelete the contact (salary field ) record, hence we have to use after insert, after  update, after delete and after undelete trigger events.

There are two approaches to solve this problem one is using the inbuilt aggregate function in salesforce and the second one is to build your own logic for calculating maximum salary and minimum salary.
The great news for all of you is we will try to solve the scenario using both methods.


Solution 1:Using Aggregate functions min() and max() to calculate the maximum and minimum salary.

Code:

trigger MaxMinSalaryCal on Contact(after insert,after update,after delete,after undelete) {
    Set<Id> accids= new Set<id>();
    List<Account> updateList=new List<Account>();
    if(Trigger.isInsert|| Trigger.isUpdate||Trigger.isUndelete){
        for(Contact c:trigger.new)
        {
            accids.add(c.accountid);
        }    }
    if(Trigger.isDelete){
        for(Contact c1:Trigger.old){
            accids.add(c1.accountid);
        }
    }
    for(AggregateResult result:[select accountid accid,max(salary__C) maxSalary,min(salary__c) minsalary from contact where accountid in: accids group by accountid])               
    {
        Account a= new Account();
        a.MaxSalary__c=(Decimal) result.get('maxSalary');  
        a.MinSalary__c=(Decimal)result.get('minsalary');
        a.id=(Id)result.get('accid');
        updateList.add(a);                                       
    }
    update updateList;   
}


To know more about Aggregate Functions, Please click  the below link of an official document by Salesforce


Solution 2:Without using Aggregate Functions 

The crux of the logic is arranging the salary of all contacts in descending order and then the first element of the list will contain the max amount(i.e max salary) and the last element of the list will contain the min amount(i.e minimum salary in this case)


Code:
trigger MaxMinSalaryCal on Contact(after insert,after update,after delete,after undelete){
    Set<Id> accids= new Set<id>();
    List<Account> updateList=new List<Account>();
    if(Trigger.isInsert|| Trigger.isUpdate||Trigger.isUndelete){
    for(Contact c:trigger.new)
    {
        accids.add(c.accountid);
    }    }
    
    if(Trigger.isDelete){
        for(Contact c1:Trigger.old){
            accids.add(c1.accountid);
        }
    }
    List<Account> acclist= new List<Account>();

    acclist=[select id,name ,MaxSalary__c ,(select id,salary__c, lastname from contacts order by 
                                                      salary__c desc ) from account where id in :accids];
     for(Account a:acclist){
        List<Contact> conlist=a.contacts;
             a.MaxSalary__c=(Decimal)conlist.get(0).salary__C;
a.MinSalary__c=(Decimal)conlist.get(conlist.size()-1).salary__c;
                 updateList.add(a);
     }  
    if(updatelist.size()>0 && updatelist!=null){
    update updateList;
    }}



Thanks for reading my blog and please check out my previous blog (link mentioned below) on the trigger to learn all basic concepts about the trigger.

BONUS TIP: To implement roll-up summary logic using a trigger is the most frequently asked scenario question on triggers in salesforce developer interviews. Do prepare more for such scenario examples for the interviews.

Stay Tuned and Keep Learning and sharing your knowledge as sharing is Caring.











Monday, 21 December 2020

Episode 12:Relationship Queries in Apex -Salesforce

In this blog, we will deep dive into the concept of relationship queries. So Before wasting any time, let's let started.😊

Most of the time we need to query the data from more than one standard or custom object at a time i.e we need to traverse either from parent to child or from child to parent objects. SOQL (Salesforce Object Query Language) provides us the syntax to write these queries which are called the  Relationship Queries. We can visualize the Relationship Queries same as Joins in SQL.

Note: If you are using multiple objects in the same query to fetch the data, always remember those objects must be related to each other i.e there must be a parent -to- child or child-to-parent relationships between those objects.

Parent to Child Relationship Query

We use this query when we are referring to child object records from the parent object. Here, the main object for the query is the parent object.

Standard Object Relationship 

Let's take an example of the Account and Contact object where Account is the parent of Contact Object.

In order to traverse parent-to- child or child-to-parent relationship, relationship name is given to each relationship.


Now the question arises how can we find the relationship name between two objects.
Do not worry!It is very simple.In this case you have to find the relationship name between Account and Contact, so first open the lookup relationship field present on contact child object i.e Account Name.


Drill down on the Account Name and below screen will appears and here you can find the child relationship name which is contacts in this case.






Now once we have found out the relationship name we can write the query:

Select Name,Id,Industry,Rating ,(select Name,Phone,Email from Contacts) from Account limit 10

The above query will give below results i.e list of contacts for the given Account.


Note: Child Relationship Name in Parent-to-child relationship is always the plural of the child object name.

Custom Objects Relationship 

For Example, there are two custom objects one is  Company__c and another one is Employee__c.

One Company can have multiple employees so they share one -to -many lookup relationships where the company is the parent object and the employee is the child object. 

Now If you want to reach the employee object record from the company object, you have to write your query on the parent object (Company__c in this case)and fetch the related child records( employees).

Before writing this query we need the relationship name between those objects. Here the relationship name is employees__r.



Query Syntax :

 Select Id,Name ,(select Id,Name,Company__c from Employees__r) from Company__c


Note: When you are travesing  from parent to child in Custom Objects Relationship, then use

 plural of the child object name( without the __c)  and append an  __r .


NOTE: Only 1 Level of the nested query is allowed(  you can remember as 1 LEVEL DOWN)

Child to Parent Relationship Query

We use this query when we are referring to Parent object records from the Child object. Here, the main object for the query is the Child object.


Standard Object Relationship 




Before jumping directly to query we need to know something.Yes , you are right we need the relationship Name between two standard objects.

Lets again take the example of Account and Contact Object where Account is the parent of the Contact Object and the value of relationship name in contact is Account and you can traverse the relationship by specifying the parent using dot notation.

For Example,

SELECT Id, Account.Name, Account.Industry, Account.Rating  FROM Contact limit 10

The above query will give below results:



Custom Objects Relationship 


When you use a child-to-parent relationship, you can use dot notation with the relationship name as given below:

select id, name,company__c,company__r.name from employee__c limit 10


NOTE: You can Access up to 5 levels of parents using DOT Notation( i.e 5 LEVEL UP)


Thanks for reading my blog.Stay tuned till then keep learning and keep sharing.





 

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...