You need to sign in to do that
Don't have an account?
mukesh gupta
upsert method
Hi Expert,
I created a contact wtih (name= "AA" ,Email="aa@gmail.com"), if i insert a new contact with same Email id (name= "BB" ,Email="aa@gmail.com") then existing record will become (name= "BB" ,Email="aa@gmail.com") and new record will be delete. I want to use upsert method. this is my code please suggest where is mistake
I created a contact wtih (name= "AA" ,Email="aa@gmail.com"), if i insert a new contact with same Email id (name= "BB" ,Email="aa@gmail.com") then existing record will become (name= "BB" ,Email="aa@gmail.com") and new record will be delete. I want to use upsert method. this is my code please suggest where is mistake
Trigger NewContact on Contact (before insert) { Set<String> con = new Set<String>(); List<Contact> cont = new List<Contact>(); List<Id> duplicateIds = new List<Id>(); Map<string, Contact> existing = new Map<string, Contact>(); for (Contact c : Trigger.New) { con.add(c.Email); } for(Contact c: [SELECT Id,Email,Phone,Title FROM Contact WHERE Email IN :con]) { existing.put(c.Email, c); } if(existing.size()>0){ for (Contact c : Trigger.New) { if(existing.containsKey(c.Email)){ duplicateIds.add(c.id); Contact clone = c.clone(); clone.Id = existing.get(c.Email).Id; existing.put(c.Email, clone); } } } try { update existing.values(); Database.delete(duplicateIds); } catch (System.DmlException e) { } }
Upsert is a combination of insert and update, driven by an "External Id". So to use the upsert() call, you must create a custom 'text' field and specify it as External Id (checkbox setting when configuring a custom field). Then you can pass in objects into the upsert() api call and the salesforce.com server will figure out if that record exists (by checking if that external id value exists or not). If it does exist, the record gets updated. If the external id doesn't exist in salesforce.com, the record gets inserted.
Thanks,
Arvind Kumar
I think your requirement does not need any Triggers. It can be achieved by creating a matching rule by Email on Contact and Creating a Duplicate Rule.
Accordning to salesforce triggers are the last options to take. before that we should think using declarative development.
Thanks,
Prosenjit