You need to sign in to do that
Don't have an account?
Updating records using triggers
Hi i have a senario where
1. if contact email is already existed , while inserting or updating the contact ,it should throw an error (Email already exists with the name )
2. if i change the contact owner ,the related account owner should also be changed .
I have written the following code and working fine , but every time Email error is throwing for me ,even if i change the owner of contact record.
Trigger :
trigger Contacttrigger on Contact (before insert,before update ,after update) {
Contacttriggerhandler helper = new Contacttriggerhandler();
if(trigger.isBefore) {
if(trigger.isInsert || trigger.isUpdate) {
helper.checkEmailfields(trigger.new);
}
}
if(trigger.isAfter){
if(trigger.isUpdate){
helper.changeOwner(trigger.new);
}
}
}
Handler class :
public class Contacttriggerhandler {
public void checkEmailfields(List<contact> contactEmailchecks){
List<contact> contactEmails = new list<contact>();
contactEmails = [select email from contact];
for(contact con :contactEmailchecks ){
for(contact exconmail : contactEmails){
if(con.Email == exconmail.Email){
con.Email.addError('email already exists with the given email id');
}
}
}
public void changeOwner( List<contact> contactRecords){
set<Id> contactRelatedaccount = new set<Id>();
List<Account> accountUpdate = new List<Account>();
string contactOwner;
for(contact con : contactRecords){
if(con.AccountId != null){
contactOwner = con.ownerId;
contactRelatedaccount.add(con.AccountId);
}
}
for(Account linkedAccount : [select id from Account where id in : contactRelatedaccount]){
linkedaccount.ownerId = contactOwner;
accountUpdate.add(linkedAccount);
}
update accountUpdate;
}
}
as you are updating a contact record first the before update fires then after insert fires as you are not updating the email but as the email is already present in the contact records it is showing you the error, to prevent this you need to call the method with only those records that have a change in email.
The changes I have made are made in bol and you can try checking the above snippet and modify it accordingly.
Let me know if this helps and please close the thread by marking this as the best answer so that it can help others in the future.
Thanks.
All Answers
as you are updating a contact record first the before update fires then after insert fires as you are not updating the email but as the email is already present in the contact records it is showing you the error, to prevent this you need to call the method with only those records that have a change in email.
The changes I have made are made in bol and you can try checking the above snippet and modify it accordingly.
Let me know if this helps and please close the thread by marking this as the best answer so that it can help others in the future.
Thanks.
Can you please help me to put all the functionality of email duplicate preventor only in helper class
without having any logic in trigger