You need to sign in to do that
Don't have an account?
cambart14
Linking a New Child Record to an Existing Parent Record Before Insert
Hello! We have a custom object (Invoice__c) that is the child in a master-detail relationship with Accounts. Accounts have a unique number system housed in the SGN_Number__c field that is also on the invoice information that we get from our ERP system. When we insert invoices into Salesforce.com we do not want to manually map each invoice to the correct account (using the SGN Number) in Excel, but would rather have an Apex trigger automatically find the right accound and populate the account ID into the Invoice__c lookup field (Account__c).
I have written the below trigger, but cannot seem to get it to work.
Thanks,
cambart14
I have written the below trigger, but cannot seem to get it to work.
trigger updateInvoiceAccount on Oracle_Sales_History__c (before insert) { //get the SGNs and store it in a set. set<String> accountSGN = new set<String>(); for(Invoice__c i: trigger.new){ accountSGN.add(i.SGN_Number__c); } //query the account records and get the associated ids. map<string, Account> accountMap = new map<string, Account>([SELECT Id from Account where Id IN: accountSGN]); //update the account value based on the SGN in the record. for(Invoice__c i: trigger.new){ i.Account__c = accountMap.get(i.SGN_Number__c).Id; } }
Thanks,
cambart14
1. Handle situations where you might not have value in SGN_Number__c field (first For Loop)
2. Query, based on SGN_Number__c from Accounts, not based on IDs, am assuming that you are matching based on a unique code in SGN_Number__C field, so you wont be able to create a map directly as that map would be created taking ID as a key, where-as you might want to take SGN_Number__c field as key
3. Add a KeyNotFound condition in your for loop before updating to avoid null value error.
4. I've added a case-check, assuming that SGN_number is alphanumeric.
Here is the updated code:
All Answers
1. Handle situations where you might not have value in SGN_Number__c field (first For Loop)
2. Query, based on SGN_Number__c from Accounts, not based on IDs, am assuming that you are matching based on a unique code in SGN_Number__C field, so you wont be able to create a map directly as that map would be created taking ID as a key, where-as you might want to take SGN_Number__c field as key
3. Add a KeyNotFound condition in your for loop before updating to avoid null value error.
4. I've added a case-check, assuming that SGN_number is alphanumeric.
Here is the updated code: