Salesforce Script and Trigger series I

Salesforce Script and Trigger series I

Hey Guys, I have solved some questions which i think was really helpful for me, so I thought sharing them would be a help for you all, here is my 1st series of Salesforce trigger.

So let’s start by solving some requirements below.

Requirement 1:

Let’s look into the scenario where 2 people John and Alice would like to book their honeymoon trip with the company named ‘Travel Agency’ which is based upon salesforce CRM.

They  have planned for following location visits:

  1. New York
  2. New Jersey
  3. Georgia
  4. California
  5. Texas
  6. Virginia

From Admin point of view this particular scenario need to be logged into CRM for :

Create a Custom Object Plan With Two Required fields.

  1. Travel Hours(Integers)
  2. Travel Location (New York,New Jersey,Georgia,California,Texas,Virginia) Multipicklist.

(I) Write a script to get the total hours of all the Plans record having Multipicklist New York or Virginia selected only or with other values.

(II) Write a Trigger to Stop creating any more Plan records with location ‘New York‘ if we have ‘Travel Hours’ more than 100 hours for any specific location ‘New York‘. Example:

If ‘John and Alice’ want spend  time in New york and have total no of hours for all the Plans for ‘New York’ is 90 hours, for ‘New Jersey’ is 70 hours and for  ‘Georgia’ is 100 hours. Follow some given steps as:

  • A new Plan is getting created on ’New York’ with John and Alice in addition to previously added  5 hours. Then Trigger will not stop,  as total hours will become 95 hours.
  • A new Plan is getting created on ‘New Jersey’ hours 45 hours. Trigger should stop as total hours will become 105 hours.

Solution 1:

(I) Script
public class GetHours{
 // To get The Required Data
public static void gethrs(){
List Plist=new List< Plan__c>();
 Plist=[select Travel_Hours__c from Plan__c where Travel__c='A' OR Travel__c='F' OR Travel__c includes('B,C,D,E;A') OR Travel__c includes('B,C,D,E;F')];
 //Getting ALL THE from Plan__c Object
 Decimal hrs=0;
for(Plan__c pc:Plist){
 hrs=hrs + pc.Travel_Hours__c;
 }
System.debug('TOTAL HOURS-->'+hrs);
 }
}
(II)Trigger
List pcList=Trigger.New;
List pcListnew= [select Travel_Hours__c from Plan__c where Travel__c ='A'];
 // or Travel__c includes('A')];
System.debug('get list---------'+pcListnew);
Decimal totalHr=0;
for(Plan__c pchr:pcListnew){
 totalHr= totalHr + pchr.Travel_Hours__c;
  }
for(Plan__c pc:pcList){
  if(totalHr + pc.Travel_Hours__c >100 && pc.Travel__c=='A')
     pc.addError('YOU CAN NOT ADD MORE WITH LOCATION ----> A');
 }
}

Requirement 2:

A Event organizing company which organize Dahi Handi Event and they organize the festival of Dahi Handi in societies, groups and different companies.

From Admin point of view this particular scenario need to be logged into CRM for :

“Create an Object “”Event“” (Name Default field and “”Event Date”” Date time field).

Another Junction Object ““Event Participant“” with 3 fields

1. lookup Contact

2.lookup Event

3. Attendee multipicklist(“”Attendee Contact“”,””Presenter Contact“”,””Organizer Contact“”)

(I) Write a script to create 10 “”Event Participant”” 4 with “”Attendee Contact””, 4 with “”Presenter Contact””, 2 with “”Organizer Contact””.”

(II) “Please solve the script question first.

Write a trigger to make sure No Event is having the same Contact registered as Attendee twice.

Explanation : A user named Nick is not allowed to create Two Event participant with same contact Lookup value under same Event.”

Solution 2:

(I) Script
public with sharing class CreateEventParticipent{
public static void eventCreate(){
List ConList=new List();
for(Integer i=1;i<=10;i++){
 Contact con=new Contact();
 con.LastName='TEST cont'+i+' F';
 ConList.add(con);
 }
if(ConList.size()>0)
 insert ConList;
/system.debug(con);
Event__c even=new Event__c();
even.Name='Salesforce meeting';
//even.Event_Date__c=6/02/2017 3:25 AM;
 insert even;
 System.debug(even);
 List PcList=new List();
  Integer i=0;
for(Contact con:ConList){
 Event_Participant__c evenpc = new Event_Participant__c();
if(i >0  &&  i <=4){
 evenpc.Name='INDIA CRICKET  '+i;
 evenpc.Participent__c='Attendee Contact';
 evenpc.Event__c=even.Id;
 evenpc.Contact__c=con.Id;
 }
else if(i>4 && i<=8){
  evenpc.Name='INDIA HOCKEY  '+i;
  evenpc.Participent__c='Presenter Contact';
  evenpc.Event__c=even.Id;
  evenpc.Contact__c=con.Id;
 }
else{
 evenpc.Name='INDIA MEN RACE '+i;
 evenpc.Participent__c='Organizer Contact';
 evenpc.Event__c=even.Id;
 evenpc.Contact__c=con.Id;
 }
PcList.add(evenpc);
System.debug('ADDDED------------------>'+evenpc);
 i++;
 }
if(PcList.size()>0){
  insert PcList;
System.debug('ADDDED------------------>'+PcList);
  }
 }
}
(II)Trigger
trigger PreventContactForMultipleEvents on Event_Participant__c (before insert, before update){ 
List EvPList=Trigger.New; 
for(Event_Participant__c epc:EvPList){ 
 for(Event_Participant__c cc:[select Id,Contact__c,Participent__c from Event_Participant__c where Contact__c!=NULL AND Participent__c !=NULL]){ 
  if(epc.Contact__c == cc.Contact__c && cc.Participent__c==epc.Participent__c){ 
   epc.addError('YOU CAN NOT ADD A SINGLE CONATCT WITH MORE THAN ONE EVENT !!!'); 
   }
  }
 } 
}

 Requirement 3:

A salesforce company named ABC and plan to launch a product in different region (ASIA, EMA, NA, SA) across the globe.They also want to sell the products to their clients which are in ASIA,EMA, NA and SA .

From Admin point of view this particular scenario need to be logged into CRM for:

  • Create a Multi picklist name In Account Object “Working in”

Picklist Values:

  1. ASIA
  2. EMA
  3. NA
  4. SA

(I) Write a script to get the total Quantity of Products sold in only Accounts working in  = ASIA.

(II) Write a Trigger to stop creating or updating Opportunities with Account having  “Working in = ASIA” and Already 2 Closed Won Opportunity under same Account.

Solution 3:

(I) Script
public class GetProQtywithAcc{    
public static void GetToatlPtoQty(){        
 List AccList=[select id,Name from Account where Working_In__c='ASIA'];        
//system.debug('ACCCC---->'+AccList);        
if(AccList.size()>0){            
  List oppList =[select id,TotalOpportunityQuantity,AccountId from Opportunity where AccountId IN:AccList AND StageName='Closed Won'];            
//system.debug('opp--->'+oppList);            
for(Opportunity opp:oppList){                
  System.debug('ACCOUNT---->'+opp.AccountId+'Number Of Product Sol--->'+opp.TotalOpportunityQuantity);            
   }        
  }    
 } 
}
(II) Trigger
public class PreventCreateOppOppCLoseWon_Trigger{
public static void PreventOppCreate(List OppList){
  //new List();
List AccList=[Select Name,Id from Account Where Working_In__c includes('ASIA')]; 
 //Getting all the account which is working in ASIA 
System.debug('ACCC-->'+AccList);
List OppCloseWonList=[Select Id, AccountId From Opportunity Where StageName='Closed Won' and AccountId IN:AccList];
  //getting id and accountid of all the opportunity where accountid is in AccList and stageName is Closed won
System.debug('opp-->'+OppCloseWonList);
for(Opportunity Opp:OppList){
 Integer add=0;</span>
for(Opportunity opp1:OppCloseWonList){
 if(opp1.AccountId==Opp.AccountId){
   add++;
  }
}
if(add>1){
  Opp.addError('CAN NOT ADD OR UPDATE NEW OPPORTUNITY !!');
  System.debug('AFTER MATCH------------------------>'+Opp.AccountId);
   }
  }
 }
}

Enjoy Coding!!

Pin It on Pinterest