Apex - For Loop

UMA forloop é uma estrutura de controle de repetição que permite escrever com eficiência um loop que precisa ser executado um número específico de vezes. Considere um caso de negócios em que somos obrigados a processar ou atualizar os 100 registros de uma vez. É aqui que a sintaxe do Loop ajuda e torna o trabalho mais fácil.

Sintaxe

for (variable : list_or_set) { code_block }

Diagrama de fluxo

Exemplo

Considere que temos um objeto Invoice que armazena informações das faturas diárias como CreatedDate, Status, etc. Neste exemplo, iremos buscar as faturas criadas hoje e que têm o status Pago.

Note - Antes de executar este exemplo, crie pelo menos um registro no Objeto Nota Fiscal.

// 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);