You need to sign in to do that
Don't have an account?
Sukriti Sharma
I want to create and update contacts when an account is created. But everytime I update an account it creates a new duplicate contact. How can i solve this?
This is the code I have written so far:
trigger CreateContact on Account (after insert, after update, after undelete) {
set<id> getaccountid =new set<id>();
for(account acc : trigger.new){
getaccountid.add(acc.id);
system.debug(acc.id);
}
list<contact> con = [SELECT id, accountid from contact where accountid in:getaccountid];
List<Contact> addCon = new List<Contact>();
for(Account acc : trigger.new){
if(acc.Create_Contact__c == true){
Contact con = new Contact();
con.Lastname = acc.Name;
con.Fax = acc.Fax;
con.Phone = acc.Phone;
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingCountry = acc.BillingCountry;
addCon.add(con);
}
insert addCon;
}
}
trigger CreateContact on Account (after insert, after update, after undelete) {
set<id> getaccountid =new set<id>();
for(account acc : trigger.new){
getaccountid.add(acc.id);
system.debug(acc.id);
}
list<contact> con = [SELECT id, accountid from contact where accountid in:getaccountid];
List<Contact> addCon = new List<Contact>();
for(Account acc : trigger.new){
if(acc.Create_Contact__c == true){
Contact con = new Contact();
con.Lastname = acc.Name;
con.Fax = acc.Fax;
con.Phone = acc.Phone;
con.MailingStreet = acc.BillingStreet;
con.MailingCity = acc.BillingCity;
con.MailingCountry = acc.BillingCountry;
addCon.add(con);
}
insert addCon;
}
}
All Answers
In the code above you are just quering the List<Contact> and you are not using that any where . You have to use two context like for insert your code works fine.
For update you have to use other such logic and try to update the existing record. Can you try and let me know if you face any issue.
This is just sample code for update scenerio
If this solution helps, Please mark it as best answer.
Thanks,
Thank you for replying. So, what I am trying to do is i want to have create and update contacts in one trigger only. I wanted to know how can I use if-else statements for this. I am still new to triggers. I want to create a contact when account is created but if there is an exsisting contact and account Iwant to update the same contact when I edit account.Currently it is making a new duplicate contact.