With some help from another question I have created this trigger that will take input from a text field Site_Code__c
on Orders__c
and populate the Site_Account__c
lookup-field with the Account
that has the same Site_Code__c
.
The issue now is that Account.Site_Code__c
is not a unique value and may bring more than one account with the code while otherwise completely unrelated. I would like to simply abort the trigger if more than one account is found to have that site code, OR if an account is not found to have the submitted site code. These records are submitted from an external web form, so I'm not sure how a failed trigger execution would affect the record insertion.
The working trigger that does not account for multiple site codes:
trigger PullOrderSiteAccount on Orders__c (before insert) {
Set<String> codes = new Set<String>();
for (Orders__c o : trigger.new) codes.add(o.Site_Code__c);
Map<String, Account> siteAccounts = new Map<String, Account>();
for (Account a : [
SELECT Site_Code__c FROM Account
WHERE Site_Code__c IN :codes
]) siteAccounts.put(a.Site_Code__c, a);
for (Orders__c o : Trigger.new)
{
Account siteAccount = siteAccounts.get(o.Site_Code__c);
Id parentId = (siteAccount == null) ? null : siteAccount.Id;
o.Site_Account__c = parentId;
}
}
After some guidance to account for multiple site codes:
Giving this error
Method does not exist or incorrect signature: [Map>].contains(String)
trigger PullOrderSiteAccount on Orders__c (before insert) {
Set<String> codes = new Set<String>();
for (Orders__c order : trigger.new) codes.add(order.Site_Code__c);
Map<String, List<Account>> siteAccounts = new Map<String, List<Account>>();
for (Account record : [SELECT Site_Code__c FROM Account WHERE Site_Code__c IN :codes]
)
{
if (!siteAccounts.contains(record.Site_Code__c)) //error here
siteAccounts.put(record.Site_Code__c, new List<Account>());
siteAccounts.get(record.Site_Code__c).add(record);
}
for (Orders__c order : trigger.new)
{
List<Account> matchingAccounts = siteAccounts.get(order.Site_Code__c);
Id parentId = (matchingAccounts != null && matchingAccounts.size() == 1) ?
matchingAccounts[0].Id : null;
order.Site_Account__c = parentId;
}
}