+ Start a Discussion
GMASJGMASJ 

Bulkify the code in @invocable method

Hi, 

Below code is working when bulk updates are make it is failing can you suggest me what might be the issue in below code. 
public class OpportunityProductPurchased{
    
    @InvocableMethod
    public static void OpplineProdPurch(List<ID> OppId){
    String[] stringList = new String[0];

    list<opportunitylineitem> oplnlst = new list<opportunitylineitem>([select id, name,f_Entitlement_Product_Description__c from opportunitylineitem where opportunityid = :OppId and isdeleted = false and product2.family like '%Subscription%']);
    list<opportunity> opplst = new list<opportunity>();

    for(opportunity opp :[select id, Products_Purchased__c from opportunity where id = :OppId]){
    for(opportunitylineitem opl : oplnlst){
     
        If (opl.f_Entitlement_Product_Description__c!=NULL){
            stringlist.add(opl.f_Entitlement_Product_Description__c);
        
        } 
    }
//Using join method to concatenate f_Entitlement_Product_Description__c field of all the opp line item records
     String allproducts = String.join(stringList, '\n'); 
     opp.Products_Purchased__c = allproducts.remove('null');
     opplst.add(opp);
    }

    if(opplst.size() > 0){
      update opplst;
    }       
  }
}

Thanks
Sam
ayu sharma devayu sharma dev
Hello 

Try using the IN operator instead of "=" in your queries for oppId list. 
 
[select id, name,f_Entitlement_Product_Description__c from opportunitylineitem where opportunityid IN :OppId and isdeleted = false and product2.family like '%Subscription%']
 
[select id, Products_Purchased__c from opportunity where id IN :OppId]
If the problem still persists then please let me know.

I also see another issue which is you are creating the following array with one record size. 
 
String[] stringList = new String[0]

So adding more values in a bulk job may give you an error. 
Update your code with these and if the problem still persists then let me know.

Regards
Ayush Sharma
Carl johnson 21Carl johnson 21
My family every time say that I am killing my time here at web, however I know I am getting know-how every day by reading this good articles. I every time spent my half an hour to read this blog’s posts everyday along with a cup of coffee. I highly recommend you if you are interested in gaming then please visit – gtacheatcode for latest cheats and commands (https://gtacheatcode.com/). And click here for world edit (https://gtacheatcode.com/minecraft-world-edit-commands/) latest commands.