Trigger Scenarios
1) Duplicate contact on same object phone and email
Trigger DuplicateRecordemailandphone on contact(before insert){
set<string> setemail = new set<string>();
set<string> setphone = new set<string>();
for(contact con:trigger.new){
setemail.add(con.email);
setphone.add(con.phone);
}
list<contact> conts = [select id,lastname,email,phone from contact where email in: setemail AND
phone in: setphone ];
for(contact contem:conts){
if(conts.size() > 0){
contem.email.addError('Duplicate email Not Allowed');
}
}
}
2) Trigger is designed to recalculate and update a custom field 'TotalAmount__c' on the related Account Records wherever opportunities are insert updated or deleted
Trigger UpdateValueAmount on Opportunity (after insert, after update, after delete){
set<id> accountIds = new set<id>();
if(Trigger.isInsert && Trigger.Isupdate){
for(opportunity opp:trigger.new){
accountIds.add(opp.AccountId);
}
}
if(Trigger.isDelete){
for(opportunity opp:trigger.old){
accountIds.add(opp.AccountId);
}
}
list<Account> updateAccounts = new list<Account>();
for(Account acc : [select id,Name, (select id,Amount from opportunities)from account where Id in : accountIds]){
Decimal totalAmount = 0;
for(opportunity opp : acc.Opportunities){
totalAmount += opp.Amount;
}
acc.TotalAmount__c = totalAmount;
updateAccounts.add(acc);
}
update updateAccounts;
}
3. Use Case:- Account Object Has Field numberofcontact__c when you create the account enter the value of 10 automatically create 10 contact record
Trigger UpdateValuesCount on Account(after insert){
list<contact> conlist = new list<contact>();
for(Account acc:Trigger.new){
integer int = acc.numberofcontact__c;
if(int.numberofcontact__c = null && int.numberofcontact__c > 0){
for(integer i=0;i<int;i++){
contact con = new contact();
con.lastname = 'Giri Kumar' + String.Valueof(i + 1);
con.firstnmae = 'Bingi';
conlist.add(con);
}
}
}
insert conlist
}
Comments
Post a Comment