+ Start a Discussion
nagendra kumar 21nagendra kumar 21 

System.ListException: Duplicate id in list: 00vj000000R4iTTAAZ line 198, column 1

Hi Everyone, 

I'm bad in coding and new to salesforce, in my team tester got this error while testing some scenario i would like to share here and hoping someone can fix this error for me,
 
Below is the error message  that he got.
 
Apex script unhandled exception by user/organization: 0057A0000016sh1/00D7A0000000Q5l Source organization: 00Dj0000001scFo (null) Visualforce Page: /apex/LogAnInteraction 
caused by: System.ListException: Duplicate id in list: 00vj000000R4iTTAAZ
Class.LogAnInteractionExtension.save: line 198, column 1
 ************
 
public with sharing class LogAnInteractionExtension {
    
    public Task task;
    public string taskId;
    public Set<Id> accContactIds = new Set<Id>();        
    public Set<Id> cmpgnContactIds = new Set<Id>();
    public List<Campaign> relatedCampaigns  {get;set;}
    public Account thisAccount {get;set;}
    public String AccName {get;set;}
    public list<CampaignWrapper> CampaignWrapperList {get;set;}
    private Task currentTaskRecord;
    public Account currentAccountRecord;
    public Contact currentContactRecord;
    public string LeadId;
    public ID accId;
    public Account acc {get;set;}
    Set<Id> selectedIdCamp = new Set<Id>();
    public List<CampaignMember> campMem= new List<CampaignMember>();
    public List<CampaignMember> updateConMem= new List<CampaignMember>(); 
    public static final String DECLINED_CM_STATUS =  'Declined'; 
    public static final String FULFILLED_CM_STATUS = 'Fulfilled';
    private final string Campaign_Activity_RecType  = Label.RT_CampaignActivity;
    public boolean isWater{get;set;}
    @testVisible private boolean testRun{get;set;}
    
    ApexPages.Standardcontroller controller;
    
    String CAMPAIGN_ACTIVITY_RECTYPEID = Schema.SObjectType.Task.getRecordTypeInfosByName().get(Campaign_Activity_RecType).getRecordTypeId();
    
    //Controller
    public LogAnInteractionExtension(ApexPages.StandardController controller) {
        //check to see if profile is water
        isWater = false;
        testRun = false;
        
        String profileName=[Select Id,Name from Profile where Id=:userinfo.getProfileId()].Name;
            for(WaterProfiles__c setting : WaterProfiles__c.getAll().values()){
                if (setting.Profile_Name__c == profileName) {
                    isWater=true;
                } 
            }
        
        this.task = (Task)controller.getRecord(); 
        this.task.Status = 'Completed';
        this.task.ActivityDate = system.today();
        this.task.Interaction_Origin__c = ''; 
        this.task.RecordTypeId = ApexPages.currentPage().getParameters().get('RecordType');
        //System.debug('@@Record Type' + this.task.RecordTypeId);
        this.task.Date_of_Activity__c = date.today();
        this.task.order__c = ApexPages.currentPage().getParameters().get('orderId');
        User u = [Select Id From User Where id = :UserInfo.getUserId()];
        task.OwnerId = u.Id;    
        this.controller = controller;
        
        if(isWater || testRun){
            LeadId = ApexPages.currentPage().getParameters().get('who_id');
            if(!String.isBlank(ApexPages.currentPage().getParameters().get('what_id'))){
                System.debug('ACC' + ApexPages.currentPage().getParameters().get('what_id'));
                this.currentAccountRecord = [Select Id From Account Where Id = :ApexPages.currentPage().getParameters().get('what_id')];
                accId = currentAccountRecord.Id;
            }
            else if(!String.isBlank(ApexPages.currentPage().getParameters().get('who_id')))
            {
                task.whoId = LeadId; 
            }
            
            else{
                
                this.currentContactRecord = [SELECT Id, AccountID from Contact WHERE ID =:ApexPages.currentPage().getParameters().get('who_id')];
                accId = currentContactRecord.AccountID;
            }
            
        }
        else{
            //fetch all the contacts present on the Account
            if(!String.isBlank(ApexPages.currentPage().getParameters().get('what_id'))){
                this.currentAccountRecord = [Select Id From Account Where Id = :ApexPages.currentPage().getParameters().get('what_id')];
                accId = currentAccountRecord.Id;
            }
            else if(!String.isBlank(ApexPages.currentPage().getParameters().get('who_id'))){
                this.currentContactRecord = [SELECT Id, AccountID from Contact WHERE ID =:ApexPages.currentPage().getParameters().get('who_id')];
                accId = currentContactRecord.AccountID;
                task.whoId = ApexPages.currentPage().getParameters().get('who_id');
                
            }
            
        }
        if(accId != null){
            task.WhatId = accId;
        }
        thisAccount = new Account();
        for(Account acc : [select id,Name,Top_200_Ranking__c,(select Id,Name from Contacts )  From Account where id = :accId ])
        {    
            thisAccount  = acc;
            
            for(Contact cnt: acc.contacts){
                accContactIds.add(cnt.Id);
            }
        }
        //fetch all the campaigns related to the Account
    relatedCampaigns = new List<Campaign>();
        getrelatedcampains();
        CampaignWrapperList = new List<CampaignWrapper>(); 
        
        Map<Id, List<SelectOption>> campaignRelatedStatus = new Map<Id, List<SelectOption>>();
        for(CampaignMemberStatus cms : [Select Id, CampaignId, Label From CampaignMemberStatus WHERE CampaignId IN :relatedCampaigns ORDER BY CampaignId]){
            SelectOption option = new SelectOption(cms.Label, cms.Label);
            if(!campaignRelatedStatus.containsKey(cms.CampaignId)){
                campaignRelatedStatus.put(cms.CampaignId, new List<SelectOption>{option});
            }
            else{
                List<SelectOption> existingValues = new List<SelectOption>();
                existingValues = campaignRelatedStatus.get(cms.CampaignId);
                existingValues.add(option);
                campaignRelatedStatus.put(cms.CampaignId,existingValues);
            }   
        }
        
        for(Campaign cmp : relatedCampaigns)
        { 
            for(CampaignMember cmpmem : cmp.CampaignMembers)
            { 
                CampaignWrapperList.add(new CampaignWrapper (cmp, cmpmem.Status, cmpmem.Name, cmpmem, campaignRelatedStatus.get(cmp.Id))); 
            }
        } 
    }
    
    public void getrelatedcampains()
    {
      for(Campaign c : [Select Name, status, StartDate, Type, Id, 
                (Select Name, CampaignId, ContactId, Status, HasResponded, Contact.AccountId
                  from CampaignMembers 
                  where Contact.AccountId  =:accId 
                  and status!=: DECLINED_CM_STATUS 
                  and status!=: FULFILLED_CM_STATUS 
                  ORDER By LastModifiedDate DESC ) 
                  from Campaign where isActive = true ])
                  
      {
        
        relatedCampaigns.add(c);
      }
       
        
    }
    public class CampaignWrapper {
        //Fetch Campaign details
        public Campaign campgn {get; set;}
        public String CampStatus {get; set;} 
        public List<SelectOption> statusValues   {get;set;}
        public String campMemName {get; set;}
        public CampaignMember campgnMember {get; set;}
        //select checkbox
        public Boolean selectCheck  {get;set;}
        public CampaignWrapper(Campaign c, String CampStatus, String campMemName, CampaignMember campgnMember, List<SelectOption> statuses) {
            campgn = c;
            selectCheck= false;
            this.CampStatus = CampStatus; 
            this.campMemName = campMemName;
            this.campgnMember = campgnMember;
            statusValues = statuses;
        }
    }
    
    public PageReference save() {
        
        String selectedcampId  = ''; 
        task.Top_200_Account__c = String.valueOf(thisAccount.Top_200_Ranking__c);
        
        List<Task> newtaskList = new List<Task>();
        Task tempTask;
        if(!CampaignWrapperList.isEmpty()) { 
            for(CampaignWrapper cm : CampaignWrapperList){ 
                
                if(cm.selectCheck == true) {
                    
        tempTask = new Task(Subject = task.Subject,RecordTypeId = CAMPAIGN_ACTIVITY_RECTYPEID,Status =task.Status,
            Top_200_Account__c = task.Top_200_Account__c,Interaction_Origin__c = task.Interaction_Origin__c,
            Activity_Account__c = task.WhatId,Activity_Descriptions__c = task.Activity_Descriptions__c,WhatId = cm.campgn.id, 
            Campaign_Member_Name__c = cm.campMemName , Campaign_Member_Status__c = cm.CampStatus );
        newtaskList.add(tempTask);
                    
                    cm.campgnMember.Status = cm.CampStatus; 
                    system.debug(cm.campgnmember);
                    updateConMem.add(cm.campgnMember);
                }
                if(cm.selectCheck) { 
                    selectedIdCamp.add(cm.campgnMember.Id); 
                    if(selectedcampId =='') 
                        selectedcampId = cm.campgnMember.Id;
                    else { 
                        selectedcampId = selectedcampId + ';'+cm.campgnMember.Id; 
                        
                    } 
                } 
            }
            
            update updateConMem;
            
            string selectcmpIds= selectedcampId ;
            this.task.selectedcampaign__c= selectcmpIds;
        } 
        try{
            if(!newtaskList.isEmpty()){
                insert newtaskList;
            }
            upsert task;
            PageReference pr = new PageReference('/'+task.Id);
            return pr;
            
        }catch(DMLException e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,Label.Log_An_Interaction_Error));
            SystemLoggingService.log(e);
            
            return null;
            
        }catch(Exception e){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage());
            ApexPages.addmessage(myMsg);
            
            return null;
        }
        
    }
    public PageReference cancel(){
        PageReference page;
        if( ApexPages.currentPage().getParameters().get('what_id') != null &&
           ApexPages.currentPage().getParameters().get('what_id') ==task.WhatId ){
               page = new PageReference('/'+task.WhatId );
           }
        else{
            page = new PageReference('/'+task.whoId);
            
        }
        page.setRedirect(true);
        return page;
    }
    
    public PageReference saveNew()
    { PageReference pr; 
     try{
         controller.save(); 
         Schema.DescribeSObjectResult describeResult = controller.getRecord().getSObjectType().getDescribe(); 
         //pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e');
         pr = new PageReference('/setup/ui/recordtypeselect.jsp?ent=Task' );
         
         pr.setRedirect(true); return pr; 
     }catch(Exception e)
     {
         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage())); return null; 
     }//try 
    }//saveNew 
    
    
}

 
Best Answer chosen by nagendra kumar 21
UC InnovationUC Innovation
It's probably because you can't have duplicate contact last names. Just change your second contact's name to something besides 'testContact1' and see if it works.

All Answers

UC InnovationUC Innovation
If it's a duplicate ID issue, you could convert that list into a set, and then back to a list before doing the DML. Update line 198 with this:
 
Set<CampaignMember> setCampMembers = new Set<CampaignMember>(updateConMem);
updateConMem = new List<CampaignMember>(setCampMembers );
​update updateConMem;

Hope that helps! Please choose best answer if this helped!
nagendra kumar 21nagendra kumar 21
@UC Innovation, Thanks for helping me Code is working now. If possible please provide your email ID here. 
nagendra kumar 21nagendra kumar 21
After updateting this change, realted test_class is failing ..
Below are the errors i'm getting 
  • System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, You're creating a duplicate record. We recommend you use an existing record instead.: []
    Stack TraceClass.Test_LogAnInteractionExtension.Test_LogAnInteractionExtension: line 18, column 1
  • Error Message   System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, You're creating a duplicate record. We recommend you use an existing record instead.: []
    Stack TraceClass.Test_LogAnInteractionExtension.Test_LogAnInteractionExtension_Save_Positive: line 66, column 1
@isTest
public with sharing class Test_LogAnInteractionExtension{
    public static testMethod void Test_LogAnInteractionExtension() {
        
        User currentUser = CreateTestClassData.reusableUser('System Administrator','TestU');
        system.runAs(currentUser){
            
            Account acc = CreateTestClassData.createCustomerAccount();
            
            Contact cont = new Contact();
            cont.LastName = 'testContact1';
            cont.AccountId = acc.Id;
            insert cont;
            
            Contact cont2 = new Contact();
            cont2.LastName = 'testContact1';
            cont2.AccountId = acc.Id;
            insert cont2;
            
            acc.Primary_Contact__c = cont.Id;
            update acc;
            
            Campaign camp = CreateTestClassData.reusableCampaign();
            insert camp ;
            
            CampaignMember cm = CreateTestClassData.reusableCampaignMember(camp.Id,cont.Id);
            insert cm; 
            
            Task tsk = CreateTestClassData.reusableTask();
            
            tsk.RecordTypeId =[Select Id,SobjectType,Name From RecordType WHERE Name ='Water Task' and SobjectType ='Task'].Id;
            tsk.OwnerId = currentUser.Id;
            tsk.WhatId = camp.Id;
            tsk.RecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Log An Interaction').getRecordTypeId();
            tsk.selectedcampaign__c = cm.id;
            insert tsk;
            
            //Call the VF page
            Test.startTest();
            ApexPages.StandardController std = new ApexPages.StandardController(tsk);
            ApexPages.currentPage().getParameters().put('what_id',acc.Id);
            LogAnInteractionExtension LogCall = new LogAnInteractionExtension(std);
            LogCall.isWater = false;
            
            Test.stopTest();
            
        }  
    }
    
     public static testMethod void Test_LogAnInteractionExtension_Save_Positive() {
        
        // Create common test accounts
        User currentUser = CreateTestClassData.reusableUser('System Administrator','TestU');
        system.runAs(currentUser){
            
            Account acc = CreateTestClassData.createCustomerAccount();
            
            Contact cont = new Contact();
            cont.LastName = 'testContact1';
            cont.AccountId = acc.Id;
            insert cont;
            
            Contact cont2 = new Contact();
            cont2.LastName = 'testContact1';
            cont2.AccountId = acc.Id;
            insert cont2;
            
            acc.Primary_Contact__c = cont.Id;
            update acc;
            
            Campaign camp = CreateTestClassData.reusableCampaign();
            insert camp;
            
            CampaignMemberStatus cms = new CampaignMemberStatus();
            cms.CampaignId = camp.Id;
            cms.IsDefault = false;
            cms.Label = 'Participated';
            cms.SortOrder = 3;
            insert cms;
            
            CampaignMember cm = CreateTestClassData.reusableCampaignMember(camp.Id,cont.Id);
            insert cm; 
            
            CampaignMember cm2 = CreateTestClassData.reusableCampaignMember(camp.Id,cont2.Id);
            insert cm2;
            
            Task tsk = CreateTestClassData.reusableTask();
            //tsk.RecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Inbound_Call').getRecordTypeId();
            tsk.OwnerId = currentUser.Id;
            tsk.WhatId = camp.Id;
            tsk.selectedcampaign__c = cm.id;
            tsk.RecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Log An Interaction').getRecordTypeId();
            System.debug('@@@ Check for Task Id' + tsk);
            insert tsk;
            
            Test.startTest();
            ApexPages.StandardController std = new ApexPages.StandardController(tsk);
            ApexPages.currentPage().getParameters().put('what_id',acc.Id);
            LogAnInteractionExtension LogCall = new LogAnInteractionExtension(std);
            LogCall.CampaignWrapperList[0].selectCheck = true ;
            LogCall.CampaignWrapperList[0].CampStatus = 'Sent';
            LogCall.save();
            LogCall.cancel();
            LogCall.saveNew();
            system.assertEquals(LogCall.CampaignWrapperList[0].CampStatus,'Sent');
            Test.stopTest();
            
        }  
    }
    
}

 
UC InnovationUC Innovation
It's probably because you can't have duplicate contact last names. Just change your second contact's name to something besides 'testContact1' and see if it works.
This was selected as the best answer
nagendra kumar 21nagendra kumar 21
It working now thanks.