Apex - Boucle For

UNE forloop est une structure de contrôle de répétition qui vous permet d'écrire efficacement une boucle qui doit s'exécuter un certain nombre de fois. Prenons une analyse de rentabilisation dans laquelle nous sommes tenus de traiter ou de mettre à jour les 100 enregistrements en une seule fois. C'est là que la syntaxe Loop aide et facilite le travail.

Syntaxe

for (variable : list_or_set) { code_block }

Représentation schématique

Exemple

Considérez que nous avons un objet Facture qui stocke des informations sur les factures quotidiennes telles que CreatedDate, Status, etc. Dans cet exemple, nous allons récupérer les factures créées aujourd'hui et avoir le statut Payé.

Note - Avant d'exécuter cet exemple, créez au moins un enregistrement dans 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);