Saleforce Difficult scenarios

difficult scenarios salesforce :

1) Faced one scenario like i have one trigger on campaign object that will help to update campaign fieds first and then based on campaign fields update it will also update leads fields.
   Because there is a look up relation between campaign and leads. But for every campaign there are more than 1 lack leads assigned which is hit two governer limits.
                a) 10000 DML rows exception.
                b) Apex CPU time limit exception.
                As a work around have implemented one batch apex logic from trigger that will update 50 Million lead records whenever campaign fields update/insert.
                This implementation would avoid both 10000 DML & CPU time limit exceed exceptions.

2) Face one more scenario like all mangers would get email notification every day whenever the approval records didn't approved by manger and submitted date more than 10 days in pending status.
   As a work around have implemented apex logic that would get query all the criteria met records from process Instance object and store all the records in temporary table.
   Created one workflow email alert on same custom object that would get fire email to Mangers.

3) I have done purging activities which would purge Billions/Millions records based on created date and take a .csv back up on daily basis without manual work.
   As a work around I have implemented new batch apex that would get delete all the criteria meets and same records we are storing in document object as a .csv file.
   Storing all the fields speared by comma.

4) Faced one scenario like--I have many Question & Answer records created in Question_Answer__c Custom Object and all Q&A's same for four theaters(AMER,EMEAR,APJ,GC).
   I have created one dynamic page which will help to display all the records in single visual force page as a input components based on theater.

5) Approval process scenario-  Parent & Child relationship between Lead, Notes&Attachement object whenever lead having at least one valid attachment then only it would eligible for approval.
   As a work around created one trigger on notes&attachement object which will update/insert/increase parent temp field and we have too many approval queues based on criteria it will go for correct approval queue.

6) We have one scenario where if any user leave the company the same user would get inactive and we have some assignment rules been defined for each and every user that needs to be deleted.
   I have implemented one trigger scenario where it will do as soon as user inacitve from user object trigger witll fire and it will get deleted assignment rules objects reords but i am getting "Mixed DML" operation here.
   Becuase i am doing operation between setup objects and non setup objects. After that i decided to ran the code snippet using @future method and issue been resolved.

7) I have created one visulforce page where it will display all the lead history records and lead records in single visualforce page. There were many records and too many query filters i used and displaying the same result in visualforce page.
   But i started getting "max view state (135KB) reached".
   As a work around i removed some filds which all are not using in visualforce page and put transient keyword for all getters and setters.
   removed large getters and converted into normal list format and used try catch finally exception blcoks at final block i clearead the list of results.


   

Custom Rollup summaries using trigger salesforce


Trigger Code :
--------------
trigger RollupSummaries_Trg on Contact (after insert,after update,after delete,after undelete) {
    //RollupSummaries_Helper.cmdRollupCalculation(trigger.newMap.Values(),trigger.isInsert,trigger.isUpdate,trigger.isAfter);
    RollupSummaries_Helper.cmdRollupCalculation(trigger.new,trigger.isInsert,trigger.isUpdate,trigger.isAfter,trigger.isDelete,trigger.isUndelete,trigger.old);
}

Helper Class :
--------------
public class RollupSummaries_Helper {
    public static Map<Id,contact> uniqueMap = new Map<Id,contact>();
    public static List<Account> finalAcc = new List<Account>();
    public static Set<Contact> conSet = new Set<Contact>();
    public static Decimal sumCount;
    public static Decimal sumMax;
    public static Decimal sumMin;
    public static Decimal sumAvg;
    public static decimal sumCountList;
    public RollupSummaries_Helper(){
    }
    public static void cmdRollupHelper(List<Contact> triggerNew){
            for(contact con : triggerNew){
              uniqueMap.put(con.AccountId,con);
          }
            for(account a : [select id,(select id from contacts) from account where id IN : uniqueMap.keySet()]){
                conSet.addAll(a.contacts);
          }
        
            List<AggregateResult> groupedResults = [select count(id) totalCount,sum(Amount__c) totalSum,Max(amount__c) totalMax,min(amount__c) totalMin,avg(amount__c) totalAvg from contact where ID IN :conSet];
            for(AggregateResult ar : groupedResults ){
                sumCount = (Decimal)ar.get('totalSum');
                sumMax = (Decimal)ar.get('totalMax');
                sumMin = (Decimal)ar.get('totalMin');
                sumAvg =  (Decimal)ar.get('totalAvg');
                sumCountList = (Decimal)ar.get('totalCount');
            }
             for(account a : [select id,Sum_Of_Contacs__c from account where id IN : uniqueMap.keySet()]){
                 a.Rollup_Sum__c = sumCount;
                 a.Sum_Of_Contacs__c =sumCount;
                 a.Rollup_Max__c = sumMax;
                 a.Rollup_Min__c = sumMin;
                 a.Rollup_Avg__c = sumAvg;
                 a.Rollup_Count__c = sumCountList;
                 
                 finalAcc.add(a);
             }
        if(!finalAcc.isEmpty()){            
            database.update(finalAcc,false);
        }
    }
    public static Set<Id> acctIds = new Set<Id>();
    public static void cmdRollupCount(List<Contact> triggerNew,List<Contact> triggerOld){
        for(Contact c : triggerNew){
      acctIds.add(c.AccountId);            
        }
        Map<Id,Account> acctMapIds = new Map<Id,Account>([select id,Rollup_Count__c,(select id from contacts) from account where id IN :acctIds]);
        for(Account a : acctMapIds.values()){
            a.Rollup_Count__c = a.contacts.size();
        }
        if(!acctMapIds.isEmpty()){
            Database.update(acctMapIds.values(),false);
        }
    }
    public static void cmdRollupCountDelete(List<Contact> triggerNew,List<Contact> triggerOld){
        for(Contact c : triggerOld){
      acctIds.add(c.AccountId);            
        }
        Map<Id,Account> acctMapIds = new Map<Id,Account>([select id,Rollup_Count__c,(select id from contacts) from account where id IN :acctIds]);
        for(Account a : acctMapIds.values()){
            a.Rollup_Count__c = a.contacts.size();
        }
        if(!acctMapIds.isEmpty()){
            Database.update(acctMapIds.values(),false);
        }
    }
    public static void cmdRollupCalculation(List<Contact> triggerNew,boolean isInsert,boolean isUpdate,boolean isAfter,boolean isDelete,boolean isUndelete,List<Contact> triggerOld){        
        if(isAfter){
            if(isInsert){
                cmdRollupHelper(triggerNew);
                //cmdRollupCount(triggerNew,triggerOld);
            }else if(isUpdate){
                cmdRollupHelper(triggerNew);
            }else if(isUndelete){
                cmdRollupHelper(triggerNew);
            }else if(isDelete){
                cmdRollupCountDelete(triggerNew,triggerOld);
            }
        }
    }
}

Salesforce Rest Api getting access token and CRUD operation in java

Connected App :
Create connected app in SFDC side and put call back url as : https://localhost:8443/_callback

CliendId and Secret :
Client_Id and Client_Secret would be generated by system automatically

Get Access Token :
Get the access token from salesforce.

Jar Files :
commons-codec-1.7.jar
commons-httpclient-3.1.jar
java-json.jar
org-apache-commons-logging.jar
org.json.jar
gson-2.2.2.jar
jackson-mapper-asl-1.2.0.jar
jackson-all-1.9.0.jar
httpcore-4.2.3.jar

Complete Java Class :

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class AccountQuery{
    private static final String clientId = "3MVG9Y6d_Btp4xp5fHfBCvTWgHlfBKxrEf0lFIt9p71zfTmei0q9P8QxoaRowTIefchOoNdY8syyWOriUKYlV";
    private static final String clientSecret = "7975635620731036814";
    // THis is meaningless in our context
    private static final String redirectUri = "https://localhost:8443/_callback";
    private static final String environment = "https://ap1.salesforce.com";  
    private static String tokenUrl = null;
   
    public static final String username = "Your userName";
public static final String password = "Your Password";

    private static String accessToken = null;
    private static String instanceUrl = null;
    public void accessTokenSFDC(){
    System.out.println("------------------------Getting a token--------------------------");      
        tokenUrl = environment + "/services/oauth2/token";
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(tokenUrl);    
        post.addParameter("grant_type", "password");
        post.addParameter("client_id", clientId);
        post.addParameter("client_secret", clientSecret);
        post.addParameter("redirect_uri", redirectUri);
        post.addParameter("username", username);
        post.addParameter("password", password);
        try {
            httpclient.executeMethod(post);
            try {
                JSONObject authResponse = new JSONObject(new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
                System.out.println("Auth response: " + authResponse.toString(2));
                accessToken = authResponse.getString("access_token");
                instanceUrl = authResponse.getString("instance_url");
                System.out.println("Got access token: " + accessToken);
                System.out.println("-------------------Request has been done--------------------------\n\n");
               
            } catch (JSONException e) {
                e.printStackTrace();              
            }
        } catch (HttpException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
   
    public static void main( String[] args ) throws Exception{  
    new AccountQuery().accessTokenSFDC();//getting access token from this method
        //new AccountQuery().CreateAccount(instanceUrl,accessToken);//responsible for create account and contact records.      
        //new AccountQuery().queryAccountObject(instanceUrl, accessToken);//responsible for query account records.
        //new AccountQuery().patch(instanceUrl, accessToken);//responsible for updating records
    //new AccountQuery().showAccountId(instanceUrl, accessToken);//responsible for query account records.
    //new AccountQuery().deleteRecords(instanceUrl, accessToken);//responsible for query account records.    
    new AccountQuery().patchRecord(instanceUrl, accessToken);
    }
    public String CreateAccount(String instanceUrl, String accessToken) throws Exception{
    System.out.println("---------------------Creating Account Record in SFDC------------------------");
    HttpClient httpclient = new HttpClient();
    JSONObject account = new JSONObject();    
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Account  name: ");
        String name = scanner.next();
        System.out.print("Enter AccountNumber  Number : ");
        String accountNumber = scanner.next();
        System.out.print("Enter AnnualRevenue  : ");
        String annualRevenue = scanner.next();
        System.out.print("Enter Description  : ");
        String description = scanner.next();
        System.out.print("Enter Industry  : ");
        String industry = scanner.next();
        System.out.print("Enter Phone : ");
        String phone = scanner.next();
        System.out.print("Enter Active (Yes/No) : ");
        String isActive = scanner.next();
        System.out.print("Enter Customer Priority : ");
        String customerPriority = scanner.next();
        System.out.print("Enter Number of Locations : ");
        String numberofLocations = scanner.next();
        System.out.print("Enter SLA (GOLD/Silver) : ");
        String slaValue = scanner.next();
       
    try{
    account.put("Name",name);
    account.put("AccountNumber",accountNumber);
    account.put("AnnualRevenue",annualRevenue);
    account.put("Description",description);
    account.put("Industry",industry);
    account.put("Phone",phone);
    account.put("Active__c",isActive);
    account.put("CustomerPriority__c",customerPriority);
    account.put("NumberofLocations__c",numberofLocations);
    account.put("SLA__c",slaValue);
   
    PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account");
    post.setRequestHeader("Authorization", "OAuth " + accessToken);
    post.setRequestEntity(new StringRequestEntity(account.toString(),"application/json","UTF-8"));    
    httpclient.executeMethod(post);
    System.out.println("Get HTTP status :"+post.getStatusCode());
    if(post.getStatusCode()==201){
    try{
    JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
    System.out.println("Create Response : "+response.toString(2));
    if(response.getBoolean("success")){
    String accountid= response.getString("id");
    System.out.println("New Record has been created withe ID : "+accountid);    
    createContactRecords(accountid,instanceUrl,accessToken);
    }
    }catch (Exception e1) {
               e1.printStackTrace();
           }
    }
    }catch (Exception e1) {
            e1.printStackTrace();
        }
    System.out.println("-----------------------Records has been create successfully-------------------------\n\n");
return null;
    }
    public String  createContactRecords(String accountid,String instanceUrl, String accessToken) throws Exception{
    HttpClient httpclientContact = new HttpClient();
   
JSONObject contact = new JSONObject();
contact.put("LastName", "SFDC-Fazu");
contact.put("AccountId",accountid);

PostMethod postContact = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Contact");
postContact.setRequestHeader("Authorization", "OAuth " + accessToken);
postContact.setRequestEntity(new StringRequestEntity(contact.toString(),"application/json","UTF-8"));
try{
httpclientContact.executeMethod(postContact);
System.out.println("Get HTTP status :"+postContact.getStatusCode());
JSONObject responseContact = new JSONObject(new JSONTokener(new InputStreamReader(postContact.getResponseBodyAsStream())));
System.out.println("Create Response : "+responseContact.toString(2));
}catch (Exception e1) {
           e1.printStackTrace();
       }
    return null;
    }
    public void queryAccountObject(String instanceUrl, String accessToken)throws Exception{
    HttpClient  httpClient= new HttpClient();
    GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/query");
    get.setRequestHeader("Authorization", "OAuth " + accessToken);
    NameValuePair[] params = new NameValuePair[1];
    params[0]=new NameValuePair("q","select id,name from account");
    get.setQueryString(params);
    try{
    httpClient.executeMethod(get);
    if(get.getStatusCode()==HttpStatus.SC_OK){
    try{
    JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
    System.out.println("Query Response :"+response.toString(2) );
    System.out.println(response.get("totalSize")+"record(s) returned \n\n");
    JSONArray results = response.getJSONArray("records");
    for(int i = 0;i < results.length();i++){
    System.out.println(results.getJSONObject(i).getString("Id")+"-----"+results.getJSONObject(i).getString("Name")+"\n" );
    }
    System.out.println("\n");
   
    }catch (Exception e1) {
               e1.printStackTrace();
           }
    }
    }catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public void showAccountId(String instanceUrl, String accessToken)throws Exception{
    HttpClient  httpClient= new HttpClient();
    GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/0019000001qmYdAAAU");
    get.setRequestHeader("Authorization", "OAuth " + accessToken);
    try{
    httpClient.executeMethod(get);
    if(get.getStatusCode()==HttpStatus.SC_OK){
    try{
    JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
    System.out.println("Query Response :"+response.toString(2) );
    java.util.Iterator iterator = response.keys();
    while(iterator.hasNext() ){
    String key = (String)iterator.next();
    String value = (String)iterator.next();
    System.out.println(key + ":"+(value !=null ? value : "")+"\n");
    }
    }catch (Exception e1) {
               e1.printStackTrace();
           }
    }
    }catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public void deleteRecords(String instanceUrl, String accessToken)throws Exception{
    Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Account  ID : ");
        String accountId = scanner.next();
    HttpClient  httpClient= new HttpClient();
    DeleteMethod deleteMethod = new DeleteMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId);
    deleteMethod.setRequestHeader("Authorization", "OAuth " + accessToken);
    try{
    httpClient.executeMethod(deleteMethod);
    System.out.println("Http Status"+deleteMethod.getStatusCode()+"Deleting account \n\n");
   
    }catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public static void patchRecord(String instanceUrl, String accessToken) throws Exception{
    Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Account  ID : ");
        String accountId = scanner.next();
    HttpClient httpClient = new HttpClient();
    JSONObject update = new JSONObject();
    try{
    update.put("name", "SFDC-Fazu patch test");
    }catch (Exception e1) {
            e1.printStackTrace();
        }
    PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId) {
    @Override public String getName() { return "PATCH"; }
    };
    post.setRequestHeader("Authorization", "OAuth " + accessToken);
    post.setRequestEntity(new StringRequestEntity(update.toString(),"application/json","UTF-8"));
    try{
    httpClient.executeMethod(post);
    System.out.println("Http Status"+post.getStatusCode()+"  updated successfully \n\n");

    }catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}



ANT Migration Tool Salesforce Step by Step Procedure

  • Extract the downloaded zip file somewhere like C:\Users\fgangana\Desktop\apache-ant-1.10.1
  • Set the path in system variables -
  • ANT_HOME - C:\Users\fgangana\Desktop\apache-ant-1.10.1\bin
  • If PATH system variable already exists then add %ANT_HOME% to your path variable, else add new PATH variable and keep this value.
  • Path-%ANT_HOME%\bin;%JAVA_HOME%\bin;C:\app\fgangana\product\11.1.0\client_1\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;%systemroot%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\
  • Also create a JAVA_HOME environment variable and set the value to the location of your JDK.
  • JAVA_HOME-C:\Program Files\Java\jdk1.7.0\bin
  • Go to command prompt and type ant -version. If it shows that ‘Apache Ant Version compiled’ then that means we are good to go.
  • still we need to dowload one more salesforce jar file-
  • extact and save it to somewhere like C:\Users\fgangana\Downloads\salesforce_ant_37.0\sample
  • open command prompt and navigate to salesforce ant file like- C:\salesforce_ant_37.0\sample> ant commands
  • Go to build.properties in salesforce_ant_37.0 and open in note pad ++ and enter salesforce credentials(password=password+securitytoken).After that dont change anything
  • Open "build.xml" and you could see many commands like -deployUnpackaged,deployCode,retrieveCode,undeployCode,deployCodeCheckOnly,quickDeploy,cancelDeploy etc.
  • For ex: if you want to retrieve components from source system run the below query ---
  • C:\salesforce_ant_37.0\sample> ant retrieveCode and hit "enter".
  • Uder "codepkg" folder need add or updatecomponents in  Package.xml.


For reference : https://www.youtube.com/watch?v=IrJ9gPQ1bbk

Package.xml could be -

<?xml version="1.0" encoding="UTF-8"?>
<Package x
        <members>*</members>
        <name>ApexClass</name>
    </types>
    <types>
        <members>*</members>
        <name>ApexPage</name>
    </types>
    <types>
        <members>*</members>
        <name>CustomObject</name>
    </types>
    <types>
        <members>*</members>
        <name>EmailTemplate</name>
    </types>
    <types>
        <members>*</members>
        <name>LiveChatAgentConfig</name>
    </types>
    <version>31.0</version>
</Package>


Salesforce Rest Integration Using Postman tool

Step 1 :
----------
Create a connect app in salesforce side-
Setup-->Apps-->Connected Apps-->Click on "New".
Connected App Name = "PostManIntegration"
Contact Email="xxxx@gmail.com"
API (Enable OAuth Settings) :-
Enable OAuth Settings=True
Callback URL=https://www.getpostman.com/oauth2/callback
Selected OAuth Scopes="Move all Available OAuth Scopes from left to right".
Click on save button.

Step 2:
---------
Open Post man tool and set authorization.
Select Type = OAuth 2.0
Click on "Get New Access Token" button and fillout the details below-
Token Name =SFDCStage
Auth URL : https://ap4.salesforce.com/services/oauth2/authorize(note:target org details)
Access Token URL = https://ap4.salesforce.com/services/oauth2/token
Client ID =3MVG9YDQS5WtC11rGKIQRhZePOsBtn5nBh78IQfLbKyCCGflGeqtOOG6eQLxyCO7fWtVWd39LVFV7fMZKS4hW
(note: client id copy&paste from connected app)
Client Secret =6074728589680506029
(note: client Secret , copy&paste from connected app)
Grant Type = Authorization Code
click on "Request Token" button.

Once you click on  "Request Token" button. new popup will be opened and ask salesforce credentials. Provide the same and say allow.


Headers :
----------
Key = Content-Type----->Value=application/json

Step 3 :
--------

Now its time to test our application. Create one apex class in same salesforce organization.
Apex Class Example:


@RestResource(urlMapping='/v1/getContacts/*')
   global with sharing class getContact {
     @Httpget
      global static list<contact> fetchAccount(){
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        Id accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        list<contact> lstcontact =[Select id,lastname,Email,leadsource from contact where Accountid=:accId];        
        return lstcontact ;
      }
   }
Step 4 :
--------
From Postman tool select "Get" method and past the below url

https://ap4.salesforce.com/services/apexrest/v1/getContacts/{Your account object id}.
Click on "Send button" and you could see the below output.












Rest API test through postman salesforce

1) go To Create -> Apps ->  Connected App
2) give name  and contact email
3) Click on Enable oauth setting  and give call back url -  https://www.getpostman.com/oauth2/callback and "Selected OAuth Scopes" and Full access
4) Save


Open post man select ouath2 and generate new access token  :-

provide details as below

Tokenname
For authorization: https://ap1.salesforce.com/services/oauth2/authorize
For token requests: https://ap1.salesforce.com/services/oauth2/token
client key
client  secret
and click save it takes you to salesforce page provide your authentication details and and click accept


In Post Man :- click on "Tokenname" - > "Add token to"  give values as "Header" from dropdown and Click on Use Token you can check one header will be added with
name Authorization


Seelct GET request, paste below url :- Refer :- https://blog.mkorman.uk/using-postman-to-explore-salesforce-restful-web-services/

https://ap1.salesforce.com/services/data/v20.0/sobjects/Lead/00Q9000000zCWwb and click send








TEST DATA AND URL's :-
https://login.salesforce.com/services/data/v37/0/sobjects/Account
https://ap1.salesforce.com/services/data/v37/0/sobjects/Account

https://ap1.salesforce.com/services/data/v20.0/sobjects/Account/0019000001oLlBR?fields=AccountNumber,BillingPostalCode
https://ap1.salesforce.com/services/data/v20.0/sobjects/Lead/00Q9000000zCWwb

https://ap1.salesforce.com/services/data/v20.0/sobjects/Account
"Authorization:Bearertoken
"Content-Type:application/json"

https://ap1.salesforce.com/services/data/v20.0/sobjects/Account/0019000001pav75AAA --retrieve

Create :-

https://ap1.salesforce.com/services/data/v20.0/sobjects/Account/
{
"name" : "Fazurulla",
"Phone" : "9848012345"
}

https://ap1.salesforce.com/services/data/v20.0/sobjects/Lead/
{
"name" : "Fazurulla G"
"Phone" : "9848012345"
"Company" : "TESTCOMPANY"
"Email" : ""f.ganaganapalli@accenture.com"
}

Salesforce trigger could allow one parent will have only one child and same parent doesn't allow duplicates

Trigger Code :
----------------
trigger restrictChildDuplicates on Contact (before Insert) {
    if(System.trigger.isInsert && System.trigger.isBefore){
        restrictContactDuplicateHelper.avoidDuplicateRecords(trigger.new);
    }
}

Helper Apex Class :
-----------------------
    public class restrictContactDuplicateHelper{
    public restrictContactDuplicateHelper(){
 
    }
    public static set<Id> accId = new set<Id>();
    public static map<Id, Set<Decimal>> accConMap = new map<Id, Set<Decimal>>();
    public static void avoidDuplicateRecords(List<Contact> conLis){
        for(Contact con : conLis){
            if(con.AccountId != null){
                accConMap.put(con.AccountId, new set<Decimal>());
            }
       }
       if(!accConMap.isEmpty()){
            for(Contact con : [Select Id,Priority__c,AccountId from Contact where AccountId =: accConMap.keySet()]){
                accConMap.get(con.AccountId).add(con.Priority__c);
            }
      }
      if(!accConMap.isEmpty()){
        for(Contact conRec : conLis){
             if(accConMap.containsKey(conRec.AccountId)){              
                 Set<Decimal> conSet = accConMap.get(conRec.AccountId);
                 if(conSet.contains(conRec.Priority__c)){
                     conRec.Priority__c.addError('Priority was registered already for the Account.');
                }
            }
         }
      }
    }
}

Featured

What is Cryptography in salesforce and what are all the algorithms provided by them ?

A). It is a security protocal between two systems. Lets say we are integration two systems without any encrytion mechanism then hackers wil...

Popular