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.





 

Saturday 7 November 2020

Episode 11:Sharing the Record using Apex in Salesforce

In this blog, we will learn about sharing the records programmatically using the apex code. But the question here arises is why do we need apex sharing when we have the sharing rules to provide additional access of records to users in salesforce.

There are certain complex business requirements where sharing rules will not work, in those scenarios, we will use apex sharing using code.

Let's take one of the use cases of those scenarios and understand how it works.
For Example, you want to share the custom object "CompetencyCourse__c with the Employee. Let's consider that every CompetencyCourse__c  has a lookup to the Employee object. In this case, sharing rules will not work as you want to give access to records that are on the related list to some users. One way to solve this problem is by manually sharing the record but it will need the interference of the record owner, which will be a hectic and manual process to do for each record thus we need the automation using code.


Before you Proceed,

To access sharing using code you have to use share objects associated with every custom as well as a standard object.
For Example, ContactShare is the sharing object for Contact Object, AccountShare is the sharing object for Account Object, and so on. Moreover, all custom objects sharing object is named as "MyCustomObject__share" where MyCustomObject is the name of the custom object.
For the scenario use case, CompetencyCourse__Share is the shared object associated with a CompetencyCourse__c  custom object.


Points To Remember:

  • Objects on the detail side of the master-detail relationship do not have an associated sharing object because in a master-detail relationship the child is tightly coupled with the parent hence detail record access will be determined by the masters sharing object and the relationship's sharing setting.
  • The object's Organization-wide default access level must not be set to the most permissive access level i.e Public Read/Write because in this case there is no need to provide additional access.

Share Object

Every share object must have the below properties defined for them:

  • ParentId: The Id of the record being shared.
  • UserOrGroupId: The Id of the user or the group with whom the objects are being shared.
  • Access Level: The permission level given to the user or the group.
  • RowCause: The reason why the group or the user has been granted sharing access.







Apex Sharing Reason:

Apex sharing reasons help the developers to track the reason why the records are shared with the user or group of users and also prevent the standard users from deleting the sharing.
Note: An Apex Sharing Reason is not available for the standard objects.RowCause is Manual for the standard object i.e apex sharing will be lost once the owner is changed.

Steps to create an apex sharing reason:

  • Click on  SetUp
  • Then go to Build->Create->Objects
  • Select the  Object(CompetencyCourse__c in our example) for which you want to create sharing reasons.
  • Then go to Apex Sharing Reasons related list.
  • Click on new, the below window will appears.

  • Enter the label for the sharing reason(EmployeeCourseAccess in our example)
  • Enter the Name for the sharing reason(EmployeeCourseAccess in our example)
  • Finally, click on the Save button.

Sharing Reason is programmatically  referenced using the below code:

Schema.CustomObject__Share.rowCause.SharingReason__c

Want to know more about Schema Class, check out the link-Schema Class

Scenario: Want o share the custom object "CompetencyCourse__c with the Employee and let's consider that every CompetencyCourse__c  has a lookup to the Employee object.

Code for Sharing the Record using Apex in Salesforce

trigger CompetencyCourse_Share on CompetencyCourse__c (after insert) {
    if(Trigger.isInsert){

        /** CompetencyCourse__Share is the sharing object for the CompetencyCourse__c object.
            courses in the list of share table       **/

        List<CompetencyCourse__Share> courses= new List<CompetencyCourse__Share>();
        //for Each CompetencyCourse__c object do the following

        for(CompetencyCourse__c c:Trigger.New){
            
            CompetencyCourse__Share employeeCourse= new CompetencyCourse__Share();

            //assigning all the properties of share object with the values as explained earlier

            employeeCourse.parentid=c.id;
            employeeCourse.UserOrGroupId=c.employee__c;
            employeeCourse.accessLevel='edit';

            //EmployeeCourseAccess is the sharing reason created for the CompetencyCourse__c object.

employeeCourse.rowCause=
Schema.CompetencyCourse__Share.rowCause.EmployeeCourseAccess__c;

            //Adding the new created share object to the list defined earlier
            courses.add(employeeCourse);

        }
        /**inserting the newly created share objects in the database and
        returning the list of Database.SaveResult which can further use to calculate the no of successful or failed records **/

        Database.SaveResult[] result= Database.insert(courses,false);
        
    }  
    

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













Sunday 27 September 2020

Episode-10: Salesforce Security Model


 



Security is always crucial to any organization which cannot be compromised at any level. Therefore understanding the security model in salesforce is very significant for the admin as well as for the developers.

The Salesforce Security model is basically classified into 3 levels:

1.Object level Security

2.Field level Security.

3.Record level Security.

Before diving into it we must also understand the organization level access to the users. As an admin, you can create the users and allow them to log in to the org from the set of IP ranges and log in hours you define for them.

By default, salesforce does not restrict the login hours or IP ranges for the user but you  as an admin can always configure it in order to increase the organization's security in the following ways:

  • Can set up the range of IP addresses at the company level i.e users outside the range are sent an activation code for login to the org.
  • Can set up the IP range at the profile level i.e those users outside this IP range will not be able to access.
  • Can define the login hours at the profile level i.e if users try to access the org outside the login hours will deny access.

Object Level Security:

Objects are like tables in the database. Object-level security is managed by the profile and the permission sets. Let's understand them in detail.


Profile: 

Profile controls what the user can access in the salesforce which means it controls the accessibility of objects, fields, page layouts, record types, apps, tabs, etc, and also controls system settings.

Accessibility of objects means what users can do with the objects ie CRED permissions.

C stands for  CREATE

R stands for READ

E stands for EDIT

D stands for DELETE.




Each user is mandatory associated with the profile. There is a special profile of the system administrator who has the superpower to access everything in the salesforce. They have View All and Modify All access in addition to CRED access to the objects and fields. 

Permission Set:

Now the question which might come in your mind is Why do we need Permission Set if the user already has the profile? Let's try to answer this and understands the concept better.

Every user is assigned one profile that provides access to the specified functions that the type of user performs but what if some users need additional access to objects and settings and you don't want to grant that additional access to everyone else having the same profile. In that case, you can assign the permission set to that particular user who needs additional access without changing his profile.

For Example:

Let's say you create a  new profile name it Custom User Profile that has read, create, and edit access on the lead object. Now you want Tom who is having the Custom User Profile also to have delete access on the lead object but you don't want all other  Custom User Profile users to have delete access on leads. So it doesn't make any sense to change the profile for Tom alone. Instead, you create the permission set having delete access on the lead object and assign it to Tom who needs it.

A user can have only one profile but can have zero or multiple permission sets assigned to him.


Field-level Security

Fields are similar to columns in the tables.

Field level security determines which fields the user can see and which  CRED permissions the user has on the fields. It can grant or restrict the visibility to individual fields based on the user profile. 

Like Object Level Security, Field-level Security is managed by the profile and the permission sets.

Profiles give baseline access to the fields and in order to give additional access to the fields other than given by the profile, we use Permission sets.



Record level Security

Records are similar to rows that contain data in the table. Record level Security controls the visibility of the records.

Record level sharing is needed when we want to share the records to the users who do not own the records. The owner of the record is the user who has created the record and has CRED access on it.

The following are the types of Record Level Security:

1.Organization-Wide Default (also known as OWD)  determine the baseline access and permissions users have to the records they don't own.

Let's see the different options available for OWD:

  • Private: The most restrictive setting is private as users cannot see records they do not own.
  • Public Read-Only: users can view the records that they do not own but they cannot edit them or transfer the records.
  • Public Read /Write: users can view and edit the records that they do not own.
  • Public Read/Write/Transfer-it allows non-owners to view, edit, and change ownership. This option only applies to leads and cases.
  • Controlled by Parent: It determines the access level of the child in the master-detail relationship as it is controlled by the parent. 

2.Role Hierarchy

Role Hierarchy is used to open up the access to records if OWD is set anything restrictive other than public Read /Write.
This is generally used in the scenario when the managers above in the role hierarchy want to access the same records as their subordinates.
This can be done by selecting Grant Access Using Hierarchies checkbox (on the Organization-wide sharing default edit page) for custom objects as it is by default selected for the standard object.

3.Sharing Rules

Role hierarchy allows us to open up the access of records vertically up in the role hierarchy pipeline of any org. But what if you want to share the records with the peers in your team or with the members of other teams then we use sharing rules to share the records horizontally. The sharing rules are used only when OWD is set anything restrictive other than public Read /Write.

  • Owner Based Sharing Rules: It allows to share the records based on roles or roles and subordinates or the public groups.
For Example, We want to share the records of the users having a role as 'Sales Manager' with everyone having a role as ' XYZ Sales Manager'.


  • Criteria Based Sharing Rules
It allows us to share the records based on the specified value in the field.



4. Manual Sharing


The record owners can also share individual records with other owners using the sharing button on the record detail page.
Manual sharing is needed only if OWD is set anything restrictive other than public Read /Write.

5. Apex Managed Sharing 

There are complex business requirements where the above record sharing rules will not work so in that case we need to write the apex code for sharing the records. We will learn about those scenarios in the next blog in detail.


Note: You can only open up the visibility of records using Role Hierarchy, Sharing Rules, or Manual Sharing or apex Sharing but you can not restrict the visibility using them more than  OWD sharing settings as OWD is the most restrictive sharing setting user should have.

Thanks for reading my blog. Stay tuned till then keep learning and keep growing. If you find it useful then like and share.😊















Wednesday 9 September 2020

Episode-9 Getter and Setter Methods in Salesforce

In this blog, we will learn about using getter and setter methods in the apex controller class. Before wasting any time lets get started😊

Saturday 15 August 2020

Episode -8 Frequently Asked Interview Questions on Batch Apex in Salesforce

 


In this blog, we will have insights about the interview questions you must prepare for the batch apex topic in salesforce.

Before reading this blog I will recommend you, read my previous blog on the batch apex to understand the concepts better. Below is the link for it:


Without wasting time, let's get started.πŸ˜‰

Friday 7 August 2020

Episode 7-Batch Apex Example in Salesforce




In this blog, we will understand why and how to write a batch apex by taking an example. Without wasting any time lets get started 😊.

Wednesday 29 July 2020

Episode 6-Asynchronous Apex-Future vs Queueable vs Batch Apex in Salesforce




In this blog, we will learn about Asynchronous Apex and the comparison between its types ie. 
Future Methods, Batch Apex, and Queueable Apex. After reading the blog you will be able to
decide when and how to use them. Before wasting time lets get started.πŸ˜ƒ

Wednesday 22 July 2020

Episode 5-The Complete Guide on Future Methods in Salesforce

In this blog, we will have insights about future methods in Salesforce. This blog will be the complete guide blog for Future Methods. Before Wasting time let's get started.😊

Saturday 18 July 2020

Episode 4-Conceptual Questions on Apex Triggers

In this blog we will have insights about the questions which are conceptual and often been asked in Interviews.
I would recommend you to go through by earlier blog on Trigger so that your concepts are clear for this blog.Read till the end to know the Bonus Tip.Before wasting time let's get startedπŸ˜„.

Sunday 12 July 2020

Episode 3-Salesforce Triggers and Scenario Based Questions

In this Blog, we will have insights about Apex Triggers and how to apply trigger concepts in real-time scenarios. This Blog is for the Beginners to Intermediate Level Developers. Read the blog till the end to know the BONUS TIP. Before wasting time let's get started.πŸ‘



The trigger is the piece of code that is executed when some specified database events occur.

Types Of Triggers:

1.Before Triggers: They are used to validate or update values of records before data is saved to the database.

2. After Triggers: They are used to access record values that are stored in the database and also when you have to make changes in other records.


Trigger Syntax:
Trigger <TriggerName> On <ObjectName> (trigger_events) {
//code 
}

You may be wondering what is Trigger Events. So ,we have 7 Trigger Events in Salesforce apex  triggers  depending upon various DML operations:

  • Before Insert
  • Before Update
  • Before Delete
  • After Insert
  • After Update
  • After Delete
  • After UnDelete

Context Variables: In order to access the records which are fired due to the Trigger, We use Context Variables in Trigger. For Example, the most commonly used Context Variables are Trigger.New and Trigger.Old.   

Trigger.New contains all the new versions of records which have caused trigger to fire.Trigger.Old contains old versions of records.

You can check out all the  Trigger Context Variables at the below link:


Check out the table to know which trigger events are allowed for 4 commonly used Trigger Context Variables.








Implementing the Trigger  Scenarios:

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.

Saturday 4 July 2020

Episode 2-Ten Most Important Topics you need to prepare for Salesforce PD1 Certification

If this is your first attempt at Salesforce Platform Developer(I)  Certification and want the one-stop platform where you can have one last revision of a few Important Topics. Yes, You are at the Correct place.
Please read the blog to know insights into some important concepts which need to be revised before appearing for your certification exam. Before Wasting Time let's get started.πŸ’ͺ Also, read till the end to know the BONUS Tip.

Saturday 27 June 2020

Episode 1- Ten Most Frequently Asked Questions for Salesforce Developer Interview

If you are preparing  for  a Salesforce  interview and you want one stop blog where you can brush up your knowledge in very less time ,you are at the correct place.Here are the list of 10 most frequently asked questions for Salesforce Developer Interview.Before wasting time ,lets get started😊.
Please read the blog till the end to know the BONUS TIP.

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