[SalesForce] Trigger – Lookup field value insertion

I am using dataloader to import data into salesforce. As it is live synchronization, there is a problem with direct insertion of lookup field values. For this reason I am writing trigger before insertion to validate and insert.

I have a invoice__c custom object and it has accounts lookup field. For lookup field, receiving input value as account name. I need to get id of the account name from accounts object and insert into invoice__c account lookup field.

I am new to the Apex code and tried few lines of code. I am able to validate and stuck in id retrievel and insertion into lookup field.

Could someone help me out. And correct me if this approach is correct for multi trigger operation.

     Trigger AccountInsert on invoice__c(before insert) {

         for(invoice__c invoiceVal : Trigger.new) {

         List<invoice__c> oldAcc = [select id, Name from Account where Name 
         = invoiceVal.Account__c];

         if(oldAcc.size()>0) {

             invoiceVal.name.addError('Account is existing');

          }
        else {
             invoiceVal.name.addError('Account is not existing');
        }
    }
 }

Best Answer

This fails the basic principle of bulkifying. You should always follow the aggregate-query-update pattern, which looks like this:

trigger GetAccountForInvoice on Invoice__c (before insert) {
  Set<String> accountNames = new Set<String>();
  Map<String, Id> accountNameToId = new Map<String, Id>();
  // Aggregate
  for(Invoice__c record: Trigger.new) {
    accountNames.add(record.Account__c);
  }
  // Query
  for(Account record: [SELECT Name FROM Account WHERE Name IN :accountNames]) {
    accountNameToId.put(record.Name.toUpperCase(), record.Id);
  }
  // Update
  for(Invoice__c record: Trigger.new) {
    if(record.Account__c != null) {
      Id accountId = accountNamesToId.get(record.Account__c.toUpperCase());
      if(accountId != null) {
        System.debug('Account was found');
      } else {
        System.debug('Account was not found');
      }
    } else {
      System.debug('Account name field was blank');
    }
  }
}
Related Topic