You need to sign in to do that
Don't have an account?
Trigger help for preventing dups
I have a number of triggers in place on the Contacts object to prevent duplicate contacts from being entered. Now that we have multiple user groups on our org, I'd like to exclude records with a particular record type. Where would I insert this into the below two triggers for example? Thanks!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
trigger ContactDuplicateTriggerAcct on Contact (before insert) { Map<String, Contact> contactLookup = new Map<String, Contact>(); List<Id> accountIds = new List<Id>(); List<String> firstNames = new List<String>(); List<String> lastNames = new List<String>(); for (Contact c : Trigger.new) { accountIds.add(c.AccountId); firstNames.add(c.FirstName); lastNames.add(c.LastName); contactLookup.put(c.AccountId + ':' + c.FirstName + ':' + c.LastName, c); }
for (Contact c : [SELECT Id, AccountId, FirstName, LastName FROM Contact WHERE (FirstName in :firstNames and LastName in :lastNames) AND AccountId in :accountIds]) { if (contactLookup.containsKey(c.AccountId + ':' + c.FirstName + ':' + c.LastName)) { contactLookup.get(c.AccountId + ':' + c.FirstName + ':' + c.LastName).LastName.addError('Contact cannot be created. A contact already exists with the same name-account combination.'); } } }
Email trigger:
|
Hello,
Try to add this query
id recordtypeid = [select id from recordtype where name='Standard' and sobject='contact'].id;
exclude the contacts with the above recordtypeid in the for using
for (Contact c : Trigger.new) {
if(c.recordtypeid != recordtypeid){
accountIds.add(c.AccountId);
firstNames.add(c.FirstName);
lastNames.add(c.LastName);
contactLookup.put(c.AccountId + ':' + c.FirstName + ':' + c.LastName, c);
}
}
Looks simple enough! Thanks for your quick reply. With the query, I get the following error for that line:
No such column 'sobject' on entity 'RecordType'.
Sorry, try sobjecttype
That worked like a charm! I thank you very much! Now I tried to modify the email dup code in a similar manner and have the following code which displays this error:
Code looks fine to me, This should work. May be try to type the code instead of copy-paste it
also add the condition in select query used to fetch Contacts. i.e.
for (Contact c : [SELECT Id, AccountId, FirstName, LastName FROM Contact
WHERE (FirstName in :firstNames and LastName in :lastNames) AND AccountId in :accountIds and recordtypeid != 'xyz''])
where xyz is 18 digit recordtype id which can be obtained from recordType Object. This will optimized.
Really appreciate the help! I finally got back to this and got the email trigger working and also incorporated the additional suggested line fo rthe record type id. Now I'm trying to figure out how to exclude a second record type and have the correct syntax. I tried one method which did not work. Any suggestions? Code is below. Thx!!