1

EDIT: ADDED ENTIRE CLASS

So I am trying to iterate through a list of sObjects and get their values. However, my FOR loops keep returning me the last row in the collection.

I put in debug statements and can see that I am selecting the lists I want, as they give me the .size() I was expecting.

However when I go to iterate through the for loop below:

for(sObject obj : objects)

It always just returns me the same entry.

Thanks in advance for any help!

Entire Code Block:

public static list<sObject> csvTosObject(List<List<String>> parsedCSV, string objectType){

    System.debug ('================================================================================== FTOEmailHandler Starting csvTosObject ');

    Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(objectType).getDescribe().getSObjectType();
    system.debug('================================================================================== You want me to make a '+objectDef);

    list<sObject> objects = new list<sObject>();
    Set<sObject> objectsToAdd = new Set<sObject>();
    Set<sObject> objectsToUpdate = new Set<sObject>();
    list<list<sObject>> objectsLists = new list<list<sObject>>();
    list<FTO__c> ftoEntries = new list<FTO__c>();
    list<string> headers = new list<string>();

    list<Contact> importContacts = new List<Contact>();
    list<Lead> importLeads = new List<Lead>();

    sObject thisObj = objectDef.newSobject();
    FTO__c thisFTOEntry = new FTO__c();

    integer rowNumber = 0;
    integer rowCount = 0;
    integer colIndex = 0;
    integer ccount = 0;
    integer lcount = 0;
    Integer ftocount = 0;

    string headerName = '';
    string headerFTOName = '';
    string ftoHeader = '';

    String entryId = '';
    string entryEmail = '';
    string entryFirstName = '';
    string entryLastName = '';
    string entryMailingStreet = '';
    string entryMailingCity = '';
    string entryMailingState = '';
    string entryMailingPostalCode = '';
    String entryCountry = '';
    string entryTitle = '';
    string entryCompanyName = '';
    string entryNote = '';
    string entryPhone = ''; 
    string entryFax = '';
    string entryJob_Function = '';
    string entryIndustry = '';


    for(list<string> row : parsedCSV)
    {
        for(string col : row)
        {
            headers.add(col);
        }
        system.debug('================================================================================== File Column Headers');
        system.debug('=================================================================================='+headers);
        break;
    }// End For to get cols

    for(list<string> row : parsedCSV)
    {
        colIndex = 0;

        if(rowNumber == 0)
        {
            rowNumber++;
            continue;
        }
        else
        {
            system.debug('================================================================================== Row Index: ' + rowNumber);
            for(string col : row)
            {                   
                headerName = 'NO';
                headerFTOName = 'NO';
                ftoHeader = headers[colIndex].trim();   

                system.debug('================================================================================== Column Name ' + ftoHeader);                

                if(ftoHeader.length() > 0){

                    if(ftoHeader == 'ReferenceNumber'){
                        headerFTOName = 'FTO_Tracking_Number__c';

                    }else if(ftoHeader == 'SubmitDate'){
                        headerFTOName = 'FTO_Date_Received__c';

                    }else if(ftoHeader == 'FirstName'){
                        headerName = 'FirstName';

                    }else if(ftoHeader == 'LastName'){
                        headerName = 'LastName';

                    }else if(ftoHeader == 'JobFunction'){
                        headerName = 'Job_Function__c';

                    }else if(ftoHeader == 'JobTitle'){
                        headerName = 'Title';

                    }else if(ftoHeader == 'CompanyName'){
                        headerName = 'Company';

                    }else if(ftoHeader == 'Email'){
                        headerName = 'Email';
                        headerFTOName = 'FTO_User_Email__c';

                    }else if(ftoHeader == 'Phone'){
                        headerName = 'Phone';

                    }else if(ftoHeader == 'Fax'){
                        headerName = 'Fax';

                    }else if(ftoHeader == 'Address'){
                        headerName = 'Street';

                    }else if(ftoHeader == 'City'){
                        headerName = 'City';

                    }else if(ftoHeader == 'State'){
                        headerName = 'State';

                    }else if(ftoHeader == 'Country'){
                        headerName = 'Country';

                    }else if(ftoHeader == 'ZipCode'){
                        headerName = 'PostalCode';

                    }else if(ftoHeader == 'RequestType'){
                        headerFTOName = 'FTO_Inquiry_Type__c';

                    }else if(ftoHeader == 'ProductDescription'){
                        headerFTOName = 'FTO_Product__c';

                    }else if(ftoHeader == 'RequestSpecifics'){
                        headerFTOName = 'FTO_Specifics__c';

                    }else if(ftoHeader == 'PreferredContactMethod'){
                        headerFTOName = 'Preferred_Contact_Method__c';

                    }else if(ftoHeader == 'Industry'){
                        headerName = 'Industry';

                    }else if(ftoHeader == 'ProductDescription'){
                        headerFTOName = 'FTO_Content__c';

                    }else if(ftoHeader == 'NoteToSupplier'){
                        headerFTOName = 'Note__c';

                    }else{
                        system.debug('================================================================================== Skipping column '+ftoHeader+', at colIndex: '+colIndex);
                    }                   

                    if( headerName != 'NO'){
                        //Add Field to object for Lead/Contact
                        system.debug('================================================================================== Adding to Object for insert/update on Lead/Contact');
                        try {                       
                            thisObj.put(headerName,col.trim());
                            system.debug('=================================================================================='+ftoHeader+' column mapped to ' + headerName+', at colIndex: '+colIndex);
                        }
                        catch(exception e){
                            system.debug('================================================================================== No corresponding SFDC field specified in header');                           
                        }
                    }

                    if( headerFTOName != 'NO' ){
                        //Add Field to object for FTO Entry
                        system.debug('================================================================================== Adding to FTO Object for insert');
                        try {                       
                            thisFTOEntry.put(headerFTOName,col.trim());
                            system.debug('=================================================================================='+ftoHeader+' column mapped to ' + headerFTOName+', at colIndex: '+colIndex);
                        }
                        catch(exception e){
                            system.debug('================================================================================== No corresponding SFDC field specified in header');                           
                        }
                    }

                    colIndex++;
                }
            } 

            // check for a matching Lead in the DB based on lastname + email
            try{    
                objects.add(thisObj);

                system.debug('================================================================================== Row '+rowNumber+' Done!');
                rowNumber++;
                system.debug('================================================================================== Next Row '+rowNumber);
                rowCount++;

            } catch (Exception qe){
                system.debug('================================================================================== Failed to Add to Objects');
            }           


            try{
                ftoEntries.add(thisFTOEntry);
                system.debug('================================================================================== FTORow '+rowNumber+' Done!');
                rowCount++;
                system.debug('================================================================================== Next Row '+rowNumber);
            }catch (Exception e){
                system.debug('================================================================================== Failed to Add to FTO Entries');
            }



        }       
        system.debug('================================================================================== Added '+rowCount+' objects for Lead/Contact update');
    }// End of FOR Parsed CSV rows

    system.debug('==============================================================================================================');
    system.debug('================================================================================== Start Contact DeDup Process');
    system.debug('==============================================================================================================');
    for (List<Contact> contacts:
      [SELECT email FROM Contact]) {
        system.debug('================================================================================== Found '+contacts.size()+' Contacts in SFDC');
        for(Contact c : contacts) {
            system.debug('================================================================================== '+objects.size()+' Objects in CSV');

            for(sObject obj : objects){
            system.debug('================================================================================== Email: '+entryEmail);

                entryEmail              = String.valueOf( obj.get('Email') );
                system.debug('================================================================================== Email: '+entryEmail);
                entryFirstName          = String.valueOf( obj.get('FirstName') );
                entryLastName           = String.valueOf( obj.get('LastName') );
                entryMailingStreet      = String.valueOf( obj.get('Street') );
                entryMailingCity        = String.valueOf( obj.get('City') );
                entryMailingState       = String.valueOf( obj.get('State') );
                entryMailingPostalCode  = String.valueOf( obj.get('PostalCode') );
                entryCountry            = String.valueOf( obj.get('Country') );
                system.debug('================================================================================== Entry in CSV: '+entryEmail+' Entry in SFDC:'+c.Email);

                if(entryEmail == c.Email){
                    system.debug('================================================================================== Found Exisitng Contact in SFDC: '+entryEmail+' Matches:'+c.Email);
                    obj.put('id',c.id);
                    obj.put('MailingStreet', entryMailingStreet); 
                    obj.put('Mailingcity', entryMailingCity); 
                    obj.put('Mailingstate', entryMailingState); 
                    obj.put('MailingpostalCode', entryMailingPostalCode); 
                    obj.put('Mailingcountry', entryMailingPostalCode); 

                    objectsToUpdate.add(obj);

                    for(FTO__c fto : ftoEntries){

                        if(fto.FTO_User_Email__c == c.Email){
                            fto.Contact__c = c.id;  
                        }
                    }

                    entryEmail              = '';
                    entryFirstName          = '';
                    entryLastName           = '';
                    entryMailingStreet      = '';
                    entryMailingCity        = '';
                    entryMailingState       = '';
                    entryMailingPostalCode  = '';
                    entryCountry            = '';

                }else{
                    system.debug('================================================================================== No Exisitng Contact in SFDC, going to Add: '+entryFirstName+' '+entryLastName);
                    objectsToAdd.add(obj);

                    entryEmail              = '';
                    entryFirstName          = '';
                    entryLastName           = '';
                    entryMailingStreet      = '';
                    entryMailingCity        = '';
                    entryMailingState       = '';
                    entryMailingPostalCode  = '';
                    entryCountry            = '';
                }

            }
        }
    }
    system.debug('===========================================================================================================');
    system.debug('================================================================================== Start Lead DeDup Process');
    system.debug('===========================================================================================================');          
    for (List<Lead> leads:
      [SELECT email FROM Lead]) {
        system.debug('================================================================================== Found '+leads.size()+' Leads in SFDC');

        for(lead l : leads) {

            for(sObject obj : objects){

                entryEmail              = String.valueOf( obj.get('Email') );
                entryFirstName          = String.valueOf( obj.get('FirstName') );
                entryLastName           = String.valueOf( obj.get('LastName') );
                entryNote               = String.valueOf( obj.get('FTO_Note__c') );
                system.debug('================================================================================== Record: '+entryFirstName+' '+entryLastName);

                if(entryEmail == l.Email){
                    system.debug('================================================================================== Found Exisitng Lead in SFDC: '+entryEmail+' Matches:'+l.Email);
                    obj.put('id',l.id);
                    obj.put('company', entryCompanyName);
                    obj.put('FTO_Note__c', entryNote);

                    objectsToUpdate.add(obj);

                    for(FTO__c fto : ftoEntries){

                        if(fto.FTO_User_Email__c == l.Email){
                            fto.Contact__c = l.id;  
                        }
                    }

                }else{
                    system.debug('================================================================================== No Exisitng Lead in SFDC, going to Add: '+entryFirstName+' '+entryLastName);
                    objectsToAdd.add(obj);
                }

            }
        }
    }
    system.debug('===============================================================================================================');
    system.debug('================================================================================== Check/Create Account Process');
    system.debug('===============================================================================================================');
    for (List<Account> accounts:
      [SELECT Name FROM Account]) {
        for(Account a : accounts) {

            for(sObject obj : objectsToUpdate){

                //*********************************************************************
                // Set some Vars for later use
                //*********************************************************************
                entryId                 = String.valueOf( obj.get('id') );
                entryEmail              = String.valueOf( obj.get('Email') );
                entryCompanyName        = String.valueOf( obj.get('Company') );
                entryNote               = String.valueOf( obj.get('FTO_Note__c') );
                entryFirstName          = String.valueOf( obj.get('FirstName') );
                entryLastName           = String.valueOf( obj.get('LastName') );
                entryMailingStreet      = String.valueOf( obj.get('Street') );
                entryMailingCity        = String.valueOf( obj.get('City') );
                entryMailingState       = String.valueOf( obj.get('State') );
                entryMailingPostalCode  = String.valueOf( obj.get('PostalCode') );
                entryTitle              = String.valueOf( obj.get('Title') );
                entryPhone              = String.valueOf( obj.get('Phone') );
                entryFax                = String.valueOf( obj.get('Fax') );
                entryIndustry           = String.valueOf( obj.get('Industry') );
                entryJob_Function       = String.valueOf( obj.get('Job_Function__c') );

                if(entryCompanyName == a.Name){
                    system.debug('================================================================================== Found Exisitng Account in SFDC: '+entryCompanyName+' Matches:'+a.Name);
                    obj.put(a.id,'AccountID');
                    objectsToUpdate.add(obj);

                }else{
                    system.debug('================================================================================== No Exisitng Account in SFDC, going to Add: '+entryCompanyName);
                    Account aToAdd = new Account();

                    aToAdd.Name                 = entryCompanyName;
                    aToAdd.BillingStreet        = entryMailingStreet;
                    aToAdd.BillingCity          = entryMailingCity;
                    aToAdd.BillingState         = entryMailingState;
                    aToAdd.BillingPostalCode    = entryMailingPostalCode;
                    aToAdd.Phone                = entryPhone;

                    objectsToAdd.add(aToAdd);
                }

            }
        }
    }

    //***************************************************************************
    // Start DML ****************************************************************
    //***************************************************************************
    system.debug('================================================================================== YAY! START DML!');
    if(objectsToAdd.size() > 0){

        List<sObject> toInsert = new List<sObject>();
        toInsert.addAll(objectsToAdd);

        system.debug('================================================================================== Try to Insert');
        try{
            insert toInsert;
            system.debug('=================================================================================='+rowCount+' Records Inserted');
        }
        catch(DMLexception e){
            System.debug('================================================================================== Insert FAILED');
        }
    }else if(objectsToUpdate.size() > 0){

        List<sObject> toUpdate = new List<sObject>();
        toUpdate.addAll(objectsToUpdate);

        system.debug('================================================================================== try to Update');
        try{
            update toUpdate;
            system.debug('=================================================================================='+rowCount+' Records Updated');
        }
        catch(DMLexception e){
            System.debug('================================================================================== Updated FAILED');
        }
    }

    return null;
}

}
2
  • are you working in Salesforce APEX? I'm gonna flag this to be migrated over to the salesforce stackexchange - actually it's a double post there and here. Mar 20 '13 at 17:55
  • Yeah I was not sure where to post as there is still the category on stackexchange (and more users), but also the SFDC stackexcahnge is beta. Either way one is ok wit me, I will make sure to delete any dups ;)
    – Red2678
    Mar 20 '13 at 18:02
7

You're getting the same data over and over again because when you build the objects list, you put the same object instance in it every time.

The code that builds the objects list is wrong, you're basically doing

o = new sobject();
for (some condition) {
   o.foo = 'bar';
   objs.add(o);
}

this is effectively the same as

o = new sobject();
objs.add(o);
objs.add(o);

i.e. you add the same instance to every item in the loop, and then mutate it on the next loop around, you need to create a new instance of the object for each time through the loop so that your list contains different instances.

5
  • So list<sObject> objects = new list<sObject>(); is declared at the top of my class, and I add to it, objects.add(stuff) in some other parts of the class. I can call objects.size() from within the loop in question and it is the size I am expecting. PS - Thanks :D
    – Red2678
    Mar 20 '13 at 18:11
  • the only time you add to objects is inside the objects loop, so if its empty, it'll always be empty.
    – superfell
    Mar 20 '13 at 18:13
  • post all your code.
    – superfell
    Mar 20 '13 at 18:13
  • Added entire class
    – Red2678
    Mar 20 '13 at 18:15
  • BOOOOOOOOOOM! I had "sObject thisObj = objectDef.newSobject();" at the top of the class. You are absolutely correct. I moved it to within the loop so that it is created fresh each time the loop goes around. Fixed! Thanks so much!
    – Red2678
    Mar 20 '13 at 18:40
4

That really seems to be a truly inefficient way to handle this situation (in fact it will most likely produce the incorrect effect). Your comparison also doesn't really make any sense as your sObject is always going to be compared to the same contact.

Set<String> emails = new Set<String>();
for(sObject obj:objects){
    emails.add(obj.get('Email'));
}

List<Contact> contacts = [SELECT Email FROM Contact WHERE Email IN :emails];
for(sObject obj:objects){
    Boolean found = false;
    for(Contact con:contacts){
        if(con.Email == obj.get('Email')){
            found = true;
            // Perform found objects logic here

            break;
        }
    }

    if(!found){
        // Perform logic for non-found objects here
    }
}

The way you are doing it is going to compare every single sObject against each Contact separately, meaning that almost all of them won't be found through your multiple iterations.


Just to clarify what I mean, let's take a look at it this way:

Contacts from SFDC:

  • john@doe.com
  • jane@doe.com

Objects being loaded:

  • john@doe.com
  • peter@doe.com
  • jane@doe.com

Your logic will do this:

john@doe.com == john@doe.com -> Found existing in SFDC - objectsToUpdate.add()
john@doe.com != peter@doe.com - > Not found in SFDC - objectsToAdd.add()
john@doe.com != jane@doe.com -> Not found in SFDC - objectsToAdd.add()
jane@doe.com != john@doe.com -> Not found in SFDC - objectsToAdd.add()
jane@doe.com != peter@doe.com -> Not found in SFDC = objectsToAdd.add()
jane@doe.com == jane@doe.com -> Found existing in SFDC - objectsToUpdate().add()

So, at the end of all of this, you have 2 records to update and 4 records to add yet your CSV only had 3 records in it to begin with. It will be adding peter@doe.com twice, adding a new john@doe.com, adding a new jane@doe.com, updating the original john@doe.com, and updating the original jane@doe.com.

The way I assume you would want it is for objectsToUpdate to have jane@doe.com and john@doe.com. Then objectsToAdd would have peter@doe.com. Only 3 records are effected then.

12
  • Actually, "..as your sObject is always going to be compared to the same contact.." that is what I want :) The sobject can have duplicates and I want to get the ID of the contact and add to the sobject if there is a match.
    – Red2678
    Mar 20 '13 at 18:27
  • I added clarification to what I was talking about. I assume you would only want to update 3 records rather than 6 in that scenario. Maybe I am wrong? Mar 20 '13 at 18:42
  • Thanks so much for this. I am going to finish getting through the DML and we will see if you were right! I may just come back and hit you up. Thanks again.
    – Red2678
    Mar 20 '13 at 18:44
  • 1
    I updated my code to pull the SOQL query out of the for loop. If it helps out, great. Either way I stand by my original assertion that based on your comments your code was going to do something different than you wanted (and it is going to loop over way more records than needed as well as run more script statements then required). I guess I am just used to writing code with more performance in mind. Good luck! Mar 25 '13 at 12:05
  • 1
    I changed my vote because of your bad attitude. I use downvotes as my only way to show I did not approve of your actions (which is the same reason why you downvoted me). You took personal offense to it when I did not mean to be offensive to you at all. I was just trying to help you out. Also, my solution did answer your question, just in a different way than you expected (as my solution would solve your problem). You should check out the FAQ here - salesforce.stackexchange.com/faq - Once again, sorry if I offended you. It was not my intention. Good luck getting the code to work. Mar 25 '13 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.