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
cherialcherial 

Error: Invalid Data.

I have a samp_obj Object which is having several records. Amount is one of the fields of each record of the samp_obj records array.                      
         I am trying to update the value of Amount filed with -99999 in each record of the array when a new record is inserted or existing record is updated. Below are the class and trigger code:

Class:
public class samps_tab_prac2 {
    public static void m1(samp_obj__c[] s1){
                                                                         Integer i;
                                                                         for(i=0;i<s1.Size();i++)
                                                                            {
                                                                                  s1[5].Amount__c=-99999;
                                                                             }
                                                                      }
                                                   }

Trigger:

trigger samps_tab_trig2 on samp_obj__c (before update, before insert) {
                                                                                                                              samp_obj__c[] s1=trigger.new;   
                                                                                                                              samps_tab_prac2.m1(s1);
                                                                                                                              }

These both codes are compiled and saved successful.

But when a record is inserted or updated through Salesforce website. Getting an Error:


                                                                         Error: Invalid Data.
                                        Review all error messages below to correct your data.
Apex trigger samps_tab_trig2 caused an unexpected exception, contact your administrator: samps_tab_trig2: execution of BeforeInsert caused by: System.ListException: List
                                 index out of bounds: 5: Class.samps_tab_prac2.m1: line 7, column 20


Please tell me a way to rectify the error.

Thanks in advance
-Nath


RickyGRickyG
Nath -

I would expect this error.  You have hardcoded a value for the array index in this code.

                                                                                  s1[5].Amount__c=-99999;

When the trigger is called, there may be less than 6 entries in the s1 array. 

In fact, you should use the variable i to reference the record in the array - that is the whole point of the FOR loop.  So your code should look like this

                                                                                  s1[i].Amount__c=-99999;

Hope this helps.