top of page

Important Trigger Solved Example

  • Writer: Abhilash Banpurkar
    Abhilash Banpurkar
  • Sep 21, 2022
  • 1 min read

1 Update Child Object based on Parent Object Field.



Trigger updatecontacttype on Account(after update){
Set<ID> accids =new Set<id>();
List<contact> updatecon =new List<contact>();

for(Account accObj:trigger.new)
{
accids.add(accobj.id);
}
List<contact> conlist =new List<Contact>([Select ID,contact__type__c,
                                        account.account_type_c from 
                                   Contact Where Account ID IN:accids]);
 for(Contact conobj:conlist)
 {
 conobj.Contact_type_c=conObj.account.Account_type_c;
 updateCon.add(conobj);
 }
 Update updateCon;
 }

2 Update a field on Parent Object based on Child object



trigger updateAccountType on Contact(After insert,After update){
set<id> accids=new set<id>();
for(contact con:Trigger.new)
{
 accids.add(con.accountid);
 }
 Map<ID,account> accMap =new map<ID,account>([Select ID,Account_type_c    
                                 from account where ID IN:accids]);
  for(Contact conobj:Trigger.new)
  {
  accMap.get(conobj.Accountid).Account_type_c=conobj.Contact_Type__c;
  }
  update accMap.Values();
  }                               

3.Create a Task Related to Account and Sobjects




trigger insertMytask on Account(after insert){
List<task> insertTask =new List<task>();
for(Account acc:trigger.new);
{
Task tsk=new Task();
tsk.Subject='Test';
tsk.WhatID=acc.id;
tsk.status='Completed';
insertTask.add(tsk);
}
insert insertTask;
}

4 Update a field on same Object.



trigger Industry on Account(before insert,before update){
for(Account Acct:trigger.new)
Acct.industry="Banking";
}

5 Send Email when Child record field will update based on Parent Criteria




trigger updateContactEmail on Account(after update){
set<ID> accids=new Set<id>();
List<contact> conup =new list<contact>();
for(Account acc:trigger.new)
{
if(acc.Rating=="Hot")
accids.add(acc.id);
}
List<contact> conlist= new List<contact>([select id,Email,accountid from Contact where AccountID IN:accids]);
for(contact con:conlist)
{
con.email='Test@gmail.com';
conUp.add(con);
}
update conUp;
Messaging.SingleEmailMessage mail=new Messaging.singleEmailMessaging();
String[]toAddress=new String[]{'xyz@gmail.com'};
mail.settoAddress(toAddresses);
mail.Subject='Update Contact';
mail.PlainTextBody='Your Contact has been Updated;
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
}


Recent Posts

See All
Important Trigger Solved Questions

Create Validation Rule on same Object. trigger oppValidate on Opportunity(before insert,before update) { for(Task tsk:trigger.new){...

 
 
 

Commentaires


bottom of page