Apex - For Loop

UN forloop è una struttura di controllo della ripetizione che consente di scrivere in modo efficiente un ciclo che deve essere eseguito un numero specifico di volte. Considera un caso aziendale in cui ci viene richiesto di elaborare o aggiornare i 100 record in una volta. È qui che la sintassi Loop aiuta e semplifica il lavoro.

Sintassi

for (variable : list_or_set) { code_block }

Diagramma di flusso

Esempio

Considera che abbiamo un oggetto Fattura che memorizza le informazioni delle fatture giornaliere come Data di creazione, Stato, ecc. In questo esempio, recupereremo le fatture create oggi e avremo lo stato Pagato.

Note - Prima di eseguire questo esempio, creare almeno un record in Invoice Object.

// Initializing the custom object records list to store the Invoice Records created today
List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();

// SOQL query which will fetch the invoice records which has been created today
PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE
   CreatedDate = today];

// List to store the Invoice Number of Paid invoices
List<string> InvoiceNumberList = new List<string>();

// This loop will iterate on the List PaidInvoiceNumberList and will process each record
for (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) {
   
   // Condition to check the current record in context values
   if (objInvoice.APEX_Status__c == 'Paid') {
      
      // current record on which loop is iterating
      System.debug('Value of Current Record on which Loop is iterating is'+objInvoice);
      
      // if Status value is paid then it will the invoice number into List of String
      InvoiceNumberList.add(objInvoice.Name);
   }
}

System.debug('Value of InvoiceNumberList '+InvoiceNumberList);