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
Girbson Bijou 8Girbson Bijou 8 

Ending position out of bounds

Hi all, 
I have a 'Text Area (Long)'  Field called  All_Products_List__c  wich will be populate by a trigger. To avoid error, i want to limit the number of caracter sto the max vaklue of Text Area (Long). 
The code  save well but when i run  the test class, The error is: "Ending position out of bounds: 131072".  
 
trigger DeliveryNotification on Item_Distributed__c (after update, after insert, after delete, after undelete){

    List <Item_Distributed__c> deliveryItems = (Trigger.isInsert|| Trigger.isUnDelete) ? Trigger.new : Trigger.old;
    
    List <Id> delveryId = new List<Id> ();
    String fullProduct;
    
    for (Item_Distributed__c allDeliveryItems : deliveryItems) {
           delveryId.add(allDeliveryItems.Delivery__c);
   }
   
   List< Delivery__c> deliveryList = [ SELECT id, All_Products_List__c, (SELECT Product_With_UOM__c  from  Items_Distributed__r ) From Delivery__c 
                                    Where id in:delveryId];
                                    
    for (Delivery__c del: deliveryList){
        if (del.Items_Distributed__r.size()>0){
            //camp.Product_With_UOM__c = string.valueOf(del.Items_Distributed [0].Product_With_UOM__c);
            del.All_Products_List__c = '';
            for(Item_Distributed__c member : del.Items_Distributed__r )
               fullProduct = del.All_Products_List__c + member.Product_With_UOM__c + ' ,';
                del.All_Products_List__c = fullProduct.substring(131072);
        }
            else
            del.All_Products_List__c = null;
        }   
                    update deliveryList;

 
Best Answer chosen by Girbson Bijou 8
David Zhu 🔥David Zhu 🔥
Based on substring defination if only one parameter applies,  the parameter is the start index.  (substring(startIndex)).
I would suggest using method substring(startIndex,endIndex)
I think line 21 in your trigger needs to be revised:
if (sullProduct.Length > 131072)
{
    del.All_Products_List__c = fullProduct.substring(0,131071);
}

All Answers

David Zhu 🔥David Zhu 🔥
Based on substring defination if only one parameter applies,  the parameter is the start index.  (substring(startIndex)).
I would suggest using method substring(startIndex,endIndex)
I think line 21 in your trigger needs to be revised:
if (sullProduct.Length > 131072)
{
    del.All_Products_List__c = fullProduct.substring(0,131071);
}
This was selected as the best answer
GauravGargGauravGarg
I agree with @David Zhu solution, just want to enhance it. 

Do add, else part:
 
if (fullProduct.Length > 131072){
    del.All_Products_List__c = fullProduct.substring(0,131071);
}else{
    del.All_Products_List__c = fullProduct;
}

Thanks,

Gaurav
skype: gaurav62990