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 InsertCSVDatafromCSV on CSVData__c (before insert) {

List<String> tmpAccountSet = new List<String>();
Map<String, String> mapAccounts = new Map<String, String>();
if( != null) {
for(CSVData__c tmpAccount : {
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;
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( != null) {
for(CSVData__c Acc : {
if(mapAccounts != null && mapAccounts.get(Acc.tempAccount__c) != null ) {
Id tempAccountid = mapAccounts.get(Acc.tempAccount__c);
Acc.Account__c = tempAccountid;


Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

Your email address will not be published. Required fields are marked *