Home SALESFORCEAPEX Importing object data from CSV file through import wizard

Consider Account and CSVData__c object. Now we wanted to import the cvs data into  CSVData__c object. Assume CSVData__c  has accountname which is lookup field and csvname. So accountname can accept only Id. So we need trigger to conert accoutname to account id. Please check the below triggering code.

Trigger:

trigger InsertCSVDatafromCSV on CSVData__c (before insert) {

List<String> tmpAccountSet = new List<String>();
Map<String, String> mapAccounts = new Map<String, String>();
if(trigger.new != null) {
for(CSVData__c tmpAccount : trigger.new) {
tmpAccountSet.add(tmpAccount.tempAccount__c);
mapAccounts.put(tmpAccount.tempAccount__c, ‘Notexist’);
}
}

List<Account> existingAccount = [Select Id, Name from Account Where Name In :tmpAccountSet];
if(existingAccount != null) {
for(Account a: existingAccount) {
mapAccounts.put(a.Name, ‘Exist’);
}
}

list<Account> insertAcc = new list<Account>();
for(Integer i=0; i<mapAccounts.size(); i++) {
string accName = tmpAccountSet.get(i);
if(mapAccounts != null && mapAccounts.get(accName) == ‘Notexist’ ) {
Account ins = new Account();
ins.Name = accName;
insertAcc.add(ins);
}
}
insert insertAcc;

List<Account> lstAccount = [Select Id, Name from Account Where Name In :tmpAccountSet];
if(lstAccount != null) {
for(Account a: lstAccount) {
mapAccounts.put(a.Name, a.Id);
}
}

if(trigger.new != null) {
for(CSVData__c Acc : trigger.new) {
if(mapAccounts != null && mapAccounts.get(Acc.tempAccount__c) != null ) {
Id tempAccountid = mapAccounts.get(Acc.tempAccount__c);
Acc.Account__c = tempAccountid;
}
}
}

}

You may also like

Leave a Comment