Thursday 10 August 2017

All Trigger Examples


In the Salesforce we can make many types of triggers on the Standard object and Custom objects.

 Basically, I will start from basic triggers and after we will go to expert level.


Trigger context variables:=

Trigger.isInsert: Returns true if the trigger was fired due to insert operation.
Trigger.isUpdate: Returns true if the trigger was fired due to update operation.
Trigger.isDelete: Returns true if the trigger was fired due to delete operation.
Trigger.isBefore: Returns true if the trigger was fired before record is saved.
Trigger.isAfter: Returns true if the trigger was fired after record is saved.
Trigger.New: Returns a list of new version of sObject records.
Trigger.Old: Returns a list of old version of sObject records.
Trigger.NewMap: Returns a map of new version of sObject records. (map is stored in the form of map)
Trigger.OldMap: Returns a map of old version of sObject records. (map is stored in the form of map)
Trigger.Size: Returns a integer (total number of records invoked due to trigger invocation for the both old and new)


1. How to field update on same object.


Trigger:



trigger Fieldupdate on Account (before insert , before update) 
{

 for(Account acc:trigger.new)
 {

 acc.Field_2__c = acc.Field_1__c;
 }

Q:1 Why we have used before event.
Ans: Whenever id already exists in salesforce and you want to update any field on the same object that time for updation we have used before event.

Salesforce has default handled dml on the same object.





2. How to give the validation error if any field is blank.


Trigger:


trigger Fieldupdate on Account (before insert , before update)
{

 for(Account acc:trigger.new)
 {
   if(acc.Field_1__c==null){

   acc.adderror('Please fill the field');

   }
 }
}

Q: Why we have used adderror.
Ans: We can do the same from validation.If you want to show error on the page so that we have used adderror  method.




Now we are Moving on List, Set, Map.


1. What is the List?


Ans: List is ordered but list allows duplicate record.


2. What is the Set?


Ans: Set is unordered but set does not contain the duplicate record.


3. What is the Map?


Ans: Map is the combination of key and value pair.


Map have 5 methods.


1. Keyset() - I will return set of keys from the map.


eg. map.keyset() = {1,2}

2. Values() - It will return list of values from the map.


eg. map.values() = {'Harsh' ,'Harshit'}


3. ContainsKey(Value) - Return true if the map contains a mapping for the specified key.


eg.  Map<String,Account>duplicateacccheck = new Map<String,Account>();


for(Account acc2:[Select Id,Name from account where name in : accname])

{
duplicateacccheck.put(acc2.name , acc2);
}
for(Account acc1 : trigger.new)
{

//Through Containskey we are fatching the name(Value) from the map

if(duplicateacccheck.containskey(acc1.name))

4. get(Key) - When we will give the key in the map and its return value.


eg. map.get(1) = it will return Harsh


5. Put(Key,Value) - Associated the specified value with the specified key in the map.


eg.  Map<Integer , String> map =  new Map<Integer , String>();

       Set<Integer>Keys
       List<String>Value

       Map.put(1,'Harsh');

       Map.put(2,'Harshit');

    { 1 -> 'Harsh' , 2 -> 'Harshit'} = 1 is key and Harsh is value.




3.How to prevent to save duplicate account.


Trigger:


trigger duplicateaccount on Account (before insert , before update) {

Set<string>accname = new Set<string>();

for(Account acc: trigger.new)
{
accname.add(acc.Name);
}

Map<String,Account>duplicateacccheck = new Map<String,Account>();

for(Account acc2:[Select Id,Name from account where name in : accname])
{
duplicateacccheck.put(acc2.name , acc2);
}
for(Account acc1 : trigger.new)
{

//Through Containskey we are fatching the name(Value) from the map
if(duplicateacccheck.containskey(acc1.name)){

acc1.adderror('You can not create duplicate account');

}
}
}




4.How to create Parent to child.

Trigger:


trigger Contactinsert on Account (after insert , after update) {

   
   List<contact>listcon = new List<contact>();

   for(Account acc : Trigger.new){

   Contact con = new Contact();

   con.AccountId = acc.id;

   con.LastName = acc.Name;

   listcon.add(con);

   }

  insert listcon;

}




5.How to create Child to parent.

Trigger:


trigger CreateAccountFromContact on Contact (before insert , before update) {
    List<Contact> needAccounts = new List<Contact>();
    for (Contact c : trigger.new) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }

    if (needAccounts.size() > 0) {
        List<Account> newAccounts = new List<Account>();
        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();

        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts;

        for (Account a : newAccounts) {

            if (contactsByNameKeys.containsKey(a.Name)) {
                contactsByNameKeys.get(a.Name).accountId = a.Id;
            }

        }


    }


}




6.How to update Parent to child.

Trigger:


trigger childupdate on Account (after update) {

 set<id>accids = new set<id>();

 for(Account acc: Trigger.new)
 {

   accids.add(acc.id);
 }

 List<contact>mapcon = [Select Accountid , id , title from contact where Accountid In:accids];

 for(contact con: mapcon)
{

Account a = Trigger.newmap.get(con.Accountid);

con.title = a.Field_1__c ;

}
update mapcon;
}




7.How to update child to parent.

Trigger:


trigger Acountupdate on Contact (after update) {


 Set<id> ids = new Set<id>();

 for(Contact con:trigger.new)
 {
 ids.add(con.AccountId);
 }

 Map<Id,account> mapVar = new Map<Id,account>([SELECT id,name,Phone FROM account WHERE Id IN : ids]);

 for(contact cont : trigger.new)
   {
 mapVar.get(cont.accountid).Phone= cont.phone;
   }
       update mapVar.values();
  }




For task creation related to any salesforce object we have used whatid and who id.

1. Whatid supported objects - 


 Contract,Order,Campaign,Account,Opportunity,Product,Asset,Case,Solution,Coaching,Goal,Metric,Asset Relationship.


2. Whoid supported objects - Contact , Lead





8.Create a Task Related to account & Sobjects

Trigger:


trigger Taskcreate on Account (after update , after insert) {

 List<Task> tasklist = new List<Task>();

 for(Account ac: Trigger.new)
 {

 Task t = new Task();

 t.Whatid = ac.id;
 t.subject = ac.name;
 tasklist.add(t);
 }

insert tasklist;

}




9. Update account Object field based on the task

Trigger:


trigger Accountupdate on Task (after insert , after update) {

 Set<id>accids = new set<id>();

 for(Task t : trigger.new)

 accids.add(t.whatid);

 Map<id,Account> mapacc = new map<id,Account>([Select id , name from Account where id In:accids]);

 for(Task t1 : trigger.new)
 {

 mapacc.get(t1.Whatid).Field_1__c = t1.subject;
 }

 update mapacc.values();

}




10.  Validation on child when any parent field is blank. 

Trigger:


trigger parentvalidate on contact (before insert , before update) {


set<id>accids = new set<id>();

for(Contact con1: trigger.new)

{

accids.add(con1.AccountId);
}

Map<id,Account>mapcon = new Map<id,Account>([Select id, Field_1__c from account where id In:accids]);

for(Contact con: trigger.new)

{

if(mapcon.get(con.AccountId).Field_1__c==null)
{
con.adderror('Please fill account Field_1__c value then you can insert account');
}
}
}




11. Prevent to deletion on any field.

Trigger:

trigger preventdeletion on Account (before delete) {


 for(Account acc: trigger.old)
 {
 if(acc.Field_1__c!=null){
 acc.adderror('You can delete the account');
 }

 }

 }




12. Prevent to delete parent if the child exists.

Trigger:

ttrigger preventaccountdelete on Account (before delete) {

 set<id> accids = new set<id>();

 for(Account acc: trigger.old)
 {

 accids.add(acc.id);

 }

 List<contact> listcon = [Select AccountId , id from contact where AccountId In:accids];

 for(contact con: listcon)
 {
 Account a = Trigger.oldmap.get(con.Accountid);
 a.adderror('you can not delete account');

 }

}




13. User will not deactivated if user is related to Teraterray OR Any Sobjects.

Trigger:

trigger userpreventtodeactive on User (before update) {

  Set<id>userid = new Set<id>();
  List<Account>accList;
  
  for(User u : [Select id,IsActive from user where id ='0057F000000JvIz']) {
  
  userid.add(u.id);
  
  }
    
   accList = [Select id,Owner.id from Account where Owner.id in:userid];  
      
       
        for(User u1:Trigger.new){
        
        if(u1.IsActive == True){
        
        u1.adderror('You can not deactivate');
        
        }
        }
        }




14. How to achieve number of contact in account(Custom Rollup summery).

Trigger:

    trigger rollUpSummaryofContact on Contact (after insert, after update, after delete, after undelete) 
{
        Set<Id> accIds = new Set<Id>();
        List<Account> accUp = new List<Account>();
        if(Trigger.isInsert || Trigger.isupdate || Trigger.isundelete)
        {
          for(Contact con : trigger.new)
          {
            accIds.add(con.accountId);
          }
        }
        
// trigger.old fetch the old records which is already in salesforce database.

        if (Trigger.isDelete)      
        {
          for(Contact con : trigger.Old)
          {
            accIds.add(con.accountId);
          }
        }

       List<account> accList = new List<account>([Select Id, Number_of_Contacts__c,(Select ID from Contacts) from Account where ID IN : accIds]);

        for(account acc : accList)
        {
            acc.Number_of_Contacts__c = acc.Contacts.size();
            accUp.add(acc);
        }

        update accUp;   

}




15. Create FeedItem & comment based on the account.





Trigger:

trigger feediteamwithcomments on contact(after insert , after update){

List<FeedItem> insertfeeditem = new List<FeedItem>();
List<FeedComment> insertfeedcomment = new List<FeedComment>();

for(Contact con : trigger.new)
{

FeedItem fI = new FeedItem();

fI.parentId = con.id;
fI.body = 'New contact has been inserted';
insertfeeditem.add(fI);
}

insert insertfeeditem;

for(FeedItem fid : insertfeeditem)
{

FeedComment comments = new FeedComment();

comments.FeedItemId = fid.id;
comments.commentbody = 'Thanks';
insertfeedcomment.add(comments);
}

insert insertfeedcomment;

}

5 comments:

  1. Good Stuff...Great learning for Salesforce beginner

    ReplyDelete
  2. Please post something related to apex class and vf pages...

    ReplyDelete
  3. Thanks for positive comment @arpit.

    Ape class and vf page under construction ..soonly i will update.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete

One particular lead takes how many days to change it's stage from one stage value to another

/*************** Ceated By    : Mohit Dwivedi( KVP Business Solution Pvt Ltd) . Created Date :  Purpose      : This  controller is for Lead ...