function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Amit Vyas 8Amit Vyas 8 

I'm inserting my custom object records related to Opportunity Line Item once a Line Item is added to opportunity but I'm not able to sort that insert list based on custom field.

Trigger is :
if(Trigger.isInsert){
                CompetitorRecordHandler.CreateRelatedCompetitor(Trigger.new);
            }

Handler class is below:
public static void CreateRelatedCompetitor(List<OpportunityLineItem> newList){
        
        List<Opportunity_Competitor__c> ocList = new List<Opportunity_Competitor__c>();
        
        for(OpportunityLineItem oli : newList){
            Opportunity_Competitor__c OppComp= new Opportunity_Competitor__c();
            
            OppComp.Forecast_Date__c=String.ValueOf(oli.ServiceDate);
            OppComp.Opportunity_Product__c=oli.Id;
            OppComp.Opportunity__c=oli.OpportunityId;
            OppComp.Product__c=oli.Product_Name__c;
            
            ocList.add(OppComp);
        }
        if(!ocList.isEmpty()){
            ocList.sort();
            insert ocList;
        }

I want to Sort my "ocList" on "Forecast_Date__c" basis. Can anyone help me?
Suraj Tripathi 47Suraj Tripathi 47
Hi Amit,

Check this code.
public static void CreateRelatedCompetitor(List<OpportunityLineItem> newList){
        
        List<Opportunity_Competitor__c> ocList = new List<Opportunity_Competitor__c>();
        
        for(OpportunityLineItem oli : newList){
            Opportunity_Competitor__c OppComp= new Opportunity_Competitor__c();
            
            OppComp.Forecast_Date__c=String.ValueOf(oli.ServiceDate);
            OppComp.Opportunity_Product__c=oli.Id;
            OppComp.Opportunity__c=oli.OpportunityId;
            OppComp.Product__c=oli.Product_Name__c;
            
            ocList.add(OppComp);
        }
        if(!ocList.isEmpty()){
            insert ocList;
        }
       List<Opportunity_Competitor__c> ocSortList =[select id, Forecast_Date__c, Opportunity_Product__c, Product__c, Opportunity__c from Opportunity_Competitor__c where Id IN: ocList ORDER BY Forecast_Date__c DESC];
   system.debug('sorted list-->>'+ocSortList);
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 
Amit Vyas 8Amit Vyas 8
Hi Suraj,

I want to insert records in the sorted order. 
Your code is inserting "ocList" then sorting it but I want to Sort "ocList" with "Forecast_Date__c " before inserting so that my Related list in Salesforce can show me records in sorted manner. 
Andrew GAndrew G
Hi Amit

If it is just for the related list, what is wrong with having the related list sorted by the page layout?
User-added image

regards
Andrew
Amit Vyas 8Amit Vyas 8
Hi Andrew,

In the related list I have sorted through "Product Name" field but I need to sort my records further with "Forecast date" so that I can have a sorted view in my related list, but related list only provide sorting using 1 field.
So once I'm able to sorf my list (With Forecast Date)before inserting records and then it will be sorted with product name through related list settings in page layout.
Ultimately I need to sort my records using "Product Name" first and then "Forecast Date" in related list.
 
Suraj Tripathi 47Suraj Tripathi 47
Hi Amit,

Check this code. Maybe, this code will help you:-
public static void CreateRelatedCompetitor(List<OpportunityLineItem> newList){
    
    map<date,Opportunity_Competitor__c> ocMap = new map<date,Opportunity_Competitor__c>();
    
    for(OpportunityLineItem oli : newList){
        Opportunity_Competitor__c OppComp= new Opportunity_Competitor__c();
        OppComp.Forecast_Date__c=String.ValueOf(oli.ServiceDate);
        OppComp.Opportunity_Product__c=oli.Id;
        OppComp.Opportunity__c=oli.OpportunityId;
        OppComp.Product__c=oli.Product_Name__c;
        ocMap.put(oli.ServiceDate,OppComp);
    }
    List<date> datList= new List<date>();
    for(date d:ocMap.keyset()){
        datList.add(d);
    }
    datList.sort();
    List<Opportunity_Competitor__c> insertocList= new List<Opportunity_Competitor__c>();
    for(date d: datList){
        insertocList.add(ocMap.get(d));
    }
    if(insertocList.size()>0){
        insert insertocList;
    }
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 
Amit Vyas 8Amit Vyas 8
Hi Suraj,

Thank you for sharing the code, I tried it but the issue is not resolved. Actually all the record dates are sorted but the 1st record is coming at last (in Enhanced Related List - Single). Don't know whether it can be resolved or not. Earlier in my code also I was facing issue with the 1st record rest all the records are inserting in a sorted manner. See the screenshot for reference. I created Line Items from 1st june till 1st November so correspondingly my custom object record should be created, all the records are apearing fine but June record is coming last. 
User-added image
 
Andrew GAndrew G
Hi Amit
One of the issues you will have is that the insert of a list happens all at once (so to speak) so there is no guarantee of the exact order each element in the list hitting the database.  A backend Salesforce person may be able to explain the exact nature of the insert and whether what you are seeing is the expected order of insert for a list.  Anecdotally, i have seen similary ordering behaviours with the insert of lists.

If this is the case, you could add something like below to code above before doing the insert:
Integer listSize = insertocList.size();
List<Opportunity_Competitor__c> finalList = new Opportunity_Competitor__c[listSize];

for(Integer i =0; i< listSize; i++) {
    if(i<ListSize) {
	finalList.add(i+1, inserttocList(i)); 
    } else {
        finalList.add(0,inserttocList(i)); 
    }
}

regards
Andrew​​​​​​​
 
Amit Vyas 8Amit Vyas 8
Hi Andrew, I tried your code but there is some syntax error in it saying "Method does not exist or incorrect signature: void inserttocList(Integer) from the type CompetitorRecordHandler". I'm not able to correct this error. 

Thank you for sharing but the issue is still not solved. 
Andrew GAndrew G
Look for the simple typo error inserttocList versus insertocList
Amit Vyas 8Amit Vyas 8
Hi Andrew,
It's more than a type error, I corrected the spellings but still getting same error message. Thanks.