0

I have below code where I try to insert an SObject and getting an error as mentioned in subject.

I have tried to fetch newly inserted records of say Object1, and putting them in Object2 lookup field before the List of Object2 records go for DML Insert.

Please find my code below where insert histories; this line is throwing exception.

Can someone please help me know how to get rid of this error?

Apex class code snippet

List<Account_Territory_Loader_vod__c> listatl = [select Id, Account_vod__c,Territory_vod__c,Territory_To_Add_vod__c, External_Id_vod__c from Account_Territory_Loader_vod__c where External_Id_vod__c in: addToTerrAccnts.keySet()];

List<Account_Territory_Loader_vod__c> updatl = new List<Account_Territory_Loader_vod__c>();
List<Account_Territory_Loader_vod__c> insatl = new List<Account_Territory_Loader_vod__c>();
List<GAS_Alignment_History_vts__c> histories = new List<GAS_Alignment_History_vts__c>();
system.debug('listatl@@'+listatl);      
system.debug('listatl size@@'+listatl.size());   
if(listatl.size()>0)
{  

    GAS_Alignment_History_vts__c history = new GAS_Alignment_History_vts__c();
    //track that Account to be aligned
    for(Account_Territory_Loader_vod__c atl: listatl)
    {
        String terr = atl.Territory_vod__c;

        if((!terr.contains(vTerrName)) && (vTerrName!=''))
        {
            atl.Territory_To_Add_vod__c = vTerrName;
            history.Old_territory__c = atl.Territory_vod__c;
            history.New_territory__c = atl.territory_vod__c + vTerrName + ';';
            system.debug('historiesNew_territory__c @@'+history.New_territory__c );
            system.debug('historiesOLD_territory__c @@'+history.Old_territory__c );
            history.Account_Territory_Loader__c = atl.Id;
            history.Account__c = atl.External_ID_vod__c;
            histories.add(history);
            updatl.add(atl);
        }
    }
} 
else
{
    for (Id ai: addToTerrAccnts.keySet())
    {
        Account_Territory_Loader_vod__c newatl = new Account_Territory_Loader_vod__c (Account_vod__c=ai, External_Id_vod__c=ai, Territory_vod__c = ';'+ vTerrName +';');
        system.debug('insert updatl@@'+ newatl);
        insatl.add(newatl);

        GAS_Alignment_History_vts__c history = new GAS_Alignment_History_vts__c();
        //track that Account to be aligned
        history.Account__c = ai;
        history.New_Territory__c = ';' + vTerrName  + ';';
        history.Old_Territory__c = '';
        histories.add(history);
    }
}

system.debug('updatl@@'+ updatl);

//ATL History

if((insatl.size()>0) || (updatl.size()>0))
{
    try
    {
        system.debug('insatl INSERT@@'+ insatl);     
        system.debug('updatl UPDATE@@'+ updatl);
        if(updatl.size()>0)
            update updatl;
        List<Id> insertedatl = new List<Id>();
        if(insatl.size()>0)
        {
            Database.SaveResult[] results = Database.insert(insatl,false);
            if (results != null)
            {
                for (Database.SaveResult result : results) 
                {
                    if (result.isSuccess())
                    {
                        insertedatl.add(result.getId());

                    }
                }

                for(Account_Territory_Loader_vod__c a: [select Id, Account_vod__c, External_Id_vod__c from Account_Territory_Loader_vod__c where Id in: insertedatl])
                {
                    for(GAS_Alignment_History_vts__c  h: histories)
                    {
                        if((h.Account__c==a.External_Id_vod__c) && (h.Account_Territory_Loader__c==null))
                            h.Account_Territory_Loader__c = a.Id;

                    }
                }
            }   

        }

        system.debug('histories@@'+histories);
        insert histories;

marked as duplicate by sfdcfox, DavidSchach, battery.cord, Basti, Oleksandr Berehovskyi Jan 22 '18 at 9:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    When asking for help with code, it truly is helpful to have a consistent coding style and indentation. I've taken care of that for you this time. Please take some time to read through the help page on formatting so you become more familiar with how to make the text of your questions look presentable (and readable) on this site. – Derek F Jan 20 '18 at 14:27
1

The problem here is that you're "recycling" the history object:

GAS_Alignment_History_vts__c history = new GAS_Alignment_History_vts__c();
//track that Account to be aligned
for(Account_Territory_Loader_vod__c atl: listatl)
{
    // ...
    histories.add(history);
    // ...
}

If you end up adding more than one item to the list, you'll end up with this error. Instead, initialize the history object inside the for loop:

for(Account_Territory_Loader_vod__c atl: listatl)
{
    String terr = atl.Territory_vod__c;

    if((!terr.contains(vTerrName)) && (vTerrName!=''))
    {
        GAS_Alignment_History_vts__c history = new GAS_Alignment_History_vts__c();
        // ...

This design choice was intentional; if you performed an insert on multiple copies of the same object, you'd lose the Id values for each of the inserted or upserted items that were duplicated in the list.

Here's a shorter snippet that demonstrates the problem:

Account a = new Account(Name='Test');
insert new Account[] { a, a };

If this code were allowed to work, you'd have two new Accounts named Test, but you'd only get one Id back (because "a" holds just one Account).

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