+ Start a Discussion
murdocmurdoc 

Help! update user lookup field

So, I have a situation where I am trying to update a custom field that is a lookup to the User record. There is a csv sheet that is being uploaded to write to this field. It gives me the first and last name and that's it. I think this needs to be done in a trigger but I am unsure where to start. The look up field is called Prospect_Owner__c which sits on an object called Exhibitors. Any help would be greatly appreciate and would come with copious amounts of thank yous and good vibes!
SandhyaSandhya (Salesforce Developers) 
Hi,

You can do with dataloader.Goto dataloader.io, login, upload your CSV, while mapping, check the "lookup via" option and select the respective name

https://focusonforce.com/integration-and-data-loading/using-dataloader-for-lookups/
 
   Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 

 
murdocmurdoc
I would love to do that, but it's part of an overall business process. I have a class set up to handle an import from our users and the only field I can get to map is the Prospect Owner which is a lookup t the user.
public with sharing class ExhibhitorListImportController {
    
    private String[] csvFileLines;
    list<Campaign> camlst = new list<Campaign>();
    public List<Campaign_Market_Sales_Plan__c> CMPlist;
    public Exhibitor_List__c objExhibitor {get;set;}
    Public Campaign objCampaign;

    public Attachment attachment {
        get {
            if(attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
    }
    /*public exhibhitorListImportController(){
        csvFileLines = new String[]{};
        VElist = New List<Exhibitor_List__c>(); 
    }*/
    
    public ExhibhitorListImportController(ApexPages.StandardController stdController) {
        
        string campaignId = ApexPages.currentPage().getParameters().get('campaignId');
        csvFileLines = new String[]{}; 
        CMPlist = new List<Campaign_Market_Sales_Plan__c>();
        objExhibitor = new  Exhibitor_List__c(Campaign__c = (Id)campaignId);
        objCampaign = new Campaign() ;
        
    } 
    
    public PageReference importCSVFile(){
        Blob csvFileBody;
        string csvAsString;

        try{
            csvAsString = attachment.Name;
            csvFileBody = attachment.Body;
            
            if(string.isBlank(csvAsString)){
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Please select csv file to upload');
                ApexPages.addMessage(errormsg);
                return null;
            }
            csvAsString = csvFileBody.toString(); 
            
            list<list<string>> lstStringRowsoflstColumns = new list<list<string>>();
            lstStringRowsoflstColumns = parseCSV(csvAsString);
            list<Exhibitor_List__c> VElist =New List<Exhibitor_List__c>();
            map<string, integer> mapduplicateKeyIntergerCount = new map<string, integer>();
            //system.debug('##--lstStringRowsoflstColumns.size(): '+ lstStringRowsoflstColumns.size());
            set<string> setUniqueKeys = new set<string>();
            Campaign_Market_Sales_Plan__c camplan = new Campaign_Market_Sales_Plan__c();
            camplan = retrieveExhibitorCampaignPlan(objExhibitor.Campaign__c); //new Campaign_Market_Sales_Plan__c();
            camplan.ListUploaded_to_Salesforce__c = TRUE;
            camplan.VEL_Import_Status__c = 'Upload Complete';
            for(Integer i=1;i<lstStringRowsoflstColumns.size();i++){
                
                list<string> csvRecordData = lstStringRowsoflstColumns[i];
                system.debug('##--csvRecordData: '+ csvRecordData); 
                Exhibitor_List__c velObj = new Exhibitor_List__c() ; 
                
                if(!string.isBlank(csvRecordData[21])){
                    velObj.Company__c = csvRecordData[21];
                }
                if(csvRecordData.size() > 25 && !string.isBlank(csvRecordData[25])){
                    velObj.Notes__c = csvRecordData[25];
                }
                if(csvRecordData.size() > 26 && !string.isBlank(csvRecordData[26])){
                    velObj.Prospect_Owner__c = csvRecordData[26];
                }

                            
                velObj.Address__c = csvRecordData[1] + '\r\n'+ csvRecordData[2] ;
                velObj.City__c = csvRecordData[3];
                velObj.State__c = csvRecordData[4];
                velObj.Postal_Code__c = csvRecordData[5];
                velObj.Country__c = csvRecordData[6];
                velObj.First_Name__c = csvRecordData[7];
                velObj.Last_Name__c = csvRecordData[8];
                velObj.Job_Title__c = csvRecordData[9];
                velObj.Name = csvRecordData[8] +', '+ csvRecordData[7];
                velObj.Phone_Number__c = csvRecordData[10];
                velObj.Email_Address__c = csvRecordData[15];
                velObj.Fax__c = csvRecordData[13];
                velObj.Booth_Stand_Number__c = csvRecordData[16];
                velObj.Booth_Stand_Width__c = csvRecordData[17];
                velObj.Booth_Stand_Depth__c = csvRecordData[18];
                velObj.Booth_Type__c = csvRecordData[19]; 
                velObj.Notes__c = csvRecordData[25];
                velObj.Prospect_Owner__c = Userinfo.getUserId();
                velObj.Prospect_Owner__c = csvRecordData[26];
                velObj.Campaign__c = objExhibitor.Campaign__c;
                velObj.Status__c = 'New';
                string uniqueKey = (objExhibitor.Campaign__c+'_'+ velObj.Email_Address__c + '_' + velObj.Company__c).toLowerCase(); 
                system.debug('##--uniqueKey: '+ uniqueKey);
                if(setUniqueKeys.contains(uniqueKey)){ 
                    if(mapduplicateKeyIntergerCount.get(uniqueKey) == null){
                        mapduplicateKeyIntergerCount.put(uniqueKey, 1);
                        uniqueKey = uniqueKey+'_dup1';
                    }else{
                        integer counter = mapduplicateKeyIntergerCount.get(uniqueKey);
                        mapduplicateKeyIntergerCount.put(uniqueKey, counter+1);
                        uniqueKey = uniqueKey+'_dup'+ counter+1;
                    }
                    //velObj.Duplicate__c = TRUE; 
                    //uniqueKey = uniqueKey+'_dup';
                    velObj.Unique_Key__c = uniqueKey; 
                    setUniqueKeys.add(uniqueKey);
                }else{
                    velObj.Unique_Key__c = uniqueKey;
                    setUniqueKeys.add(uniqueKey);
                } 
                VElist.add(velObj);   
            }// end of for-each
             
            system.debug('##--VElist: '+ VElist);
            if(VElist.size() > 0){ 
                upsert VElist Unique_Key__c;  
                if(!string.isBlank(camplan.Id)){
                    update camplan;
                } 
            }
            BatchMatchContactsOrLeads batch = new BatchMatchContactsOrLeads(objExhibitor.Campaign__c);
            database.executeBatch(batch, 1); 
            objExhibitor.Campaign__c = null;  
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.Info, 'Succesfully Uploaded '+ (lstStringRowsoflstColumns.size()-1)+' rows. You will be notified once the jobs are completed.');
            ApexPages.addMessage(errorMessage);
            attachment = null;
            
       }catch (Exception e) {
            system.debug('##--: '+ e.getLineNumber());
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'Error : ' + e.getmessage() + e.getLineNumber());
            ApexPages.addMessage(errorMessage);
            return null; 
        }
        PageReference objPageReference = new PageReference('/apex/ExhibhitorListImport');
        return objPageReference;
    }
    // Return a 2D String array with headers on first row
    public static List<List<String>> parseCSV(String contents) {
        
        System.debug('## parseCSV called with contents = ' + contents);
        // Determine if it is split by newLine(\n) or return carriage(\r) or a \r\nn
        Boolean hasNewLine = false;
        Boolean hasCarrReturn = false;
        
        //First check for a \r\n char
        if(contents.contains('\r\n')) {
            System.debug('## Contains at least one \'\\r\\n\' character');
            hasNewLine = true;
            hasCarrReturn = false;
        }
        else {
            //If not then check for either a /r or /n
            if(contents.contains('\n')) {
                System.debug('## Contains at least one newline character');
                hasNewLine = true;
            }
            if(contents.contains('\r')) {
                System.debug('## Contains at least one carriage return character');
                hasCarrReturn = true;
            }
        }
        
        List<List<String>> allFields = new List<List<String>>();
        if(hasNewLine && hasCarrReturn) {
            addError('The file contains both newline and carriage returns');
        }
        else {
            
            String splitBy = '\n';
            if(hasCarrReturn) {
                splitBy = '\r';
            }
            
            // replace instances where a double quote begins a field containing a comma
            // in this case you get a double quote followed by a doubled double quote
            // do this for beginning and end of a field
            contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
            // now replace all remaining double quotes - we do this so that we can reconstruct
            // fields with commas inside assuming they begin and end with a double quote
            contents = contents.replaceAll('""','DBLQT');
            // we are not attempting to handle fields with a newline inside of them
            // so, split on newline to get the spreadsheet rows
            List<String> lines = new List<String>();
            try {
                lines = contents.split(splitBy);
            } catch (System.ListException e) {
                System.debug('## Limits exceeded?' + e.getMessage());
            }
            System.debug('## About to check ' + lines.size() + ' lines...');
            Integer num = 0;
            
            for(String line : lines) {
                //System.debug('## Parsing line: ' + line);
                // Deal with lines where 
                //if (line.replaceAll(',','').trim().length() == 0) continue; 
                
                
                // TODO: Deal with lines where all fields empty. Currently splits into an empty array.
                
                List<String> fields = line.split(',', -1);  
                List<String> cleanFields = new List<String>();
                String compositeField;
                Boolean makeCompositeField = false;
                //System.debug('## About to read ' + fields.size() + ' fields...');
                for(String field : fields) {
                    if (field.startsWith('"') && field.endsWith('"')) {
                        cleanFields.add(field.replaceAll('DBLQT','"'));
                    } else if (field.startsWith('"')) {
                        makeCompositeField = true;
                        compositeField = field;
                    } else if (field.endsWith('"')) {
                        compositeField += ',' + field;
                        cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                        makeCompositeField = false;
                    } else if (makeCompositeField) {
                        compositeField +=  ',' + field;
                    } else {
                        cleanFields.add(field.replaceAll('DBLQT','"'));
                    }
                }
                
                // Remove double quotes (if present) from start and end of each field
                List<String> noQuoteFields = new List<String>();
                for(String field : cleanFields) {
                    system.debug('##--field: '+ field);
                    if(field.startsWith('"') && field.endsWith('"') && field.length() > 1) {
                        field = field.substring(1, field.length() - 1);
                    }
                    noQuoteFields.add(field);
                }
                allFields.add(noQuoteFields);
            }
        }
        
        // Remove any rows before header row so that header row is first row:
        Integer headerRow = -1;
        for(Integer i=0; (i < allFields.size() && headerRow == -1) ; i++) {
            // Determine if all fields in this row are non-blank:
            List<String> row = allFields.get(i);
            Boolean isHeaderRow = true;
            
            for(String field : row) {
                if(field == '') { // field is blank
                    isHeaderRow = false;
                }
            }
            
            if(isHeaderRow) {
                headerRow = i;
            }
        }
                System.debug('## headerRow ' +headerRow);
        
        for(Integer i=0; i < headerRow; i++) {
            allFields.remove(0);
        }

        System.debug('## About to return ' + allFields.size() + ' lines...');
        return allFields;
    }
    
    public static Campaign_Market_Sales_Plan__c retrieveExhibitorCampaignPlan(id CampaignId){
        
        Campaign_Market_Sales_Plan__c objCampaignPlan = new Campaign_Market_Sales_Plan__c();
        
        list<Campaign_Market_Sales_Plan__c> lstExhibitorCampaignPlan = [SELECT Id, Campaign_Plan_Type__c FROM Campaign_Market_Sales_Plan__c
                                                                                WHERE Event_Campaign_Name__c =:CampaignId limit 100];
        if(lstExhibitorCampaignPlan.size() >0 ){ 
            objCampaignPlan = lstExhibitorCampaignPlan[0]; 
        }           
        return objCampaignPlan;
        
    }// end of retrieveExhibitorCampaignPlan
    
    public static void addError(String error) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, error));
    }
}