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
giri rockzzzzgiri rockzzzz 

Problem on if ,else condition inside for loop ........

In the following code iam not able to find why the control is not executing if and else condtion when the for loop returns zero rows

 

 

 

Id a='001O0000003EcXk';
Id b='a0BO0000000EIBq';

P_L__c pl;

 for(P_L__c p:[Select Id from P_L__c Where Account__c =:a AND Billing_Period__c=:b])
        {
            if(p!=null)
{
 System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+p.id);     
}
            else
System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&error');      
        }

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

The for loop syntax you are using will only enter the enclosed block of code when there are rows in the list to process.

 

Although you are checking if p is null, this code will only be exercised if there is an element in the list.

 

If you want to test if there are any elements in the list, you'll need something like:

 

 

Id a='001O0000003EcXk';
Id b='a0BO0000000EIBq';

P_L__c pl;

List<P_L__c> pls=[Select Id from P_L__c Where Account__c =:a AND Billing_Period__c=:b];
if (pls.isEmpty())
{
System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&error');
}
else
{
  for(P_L__c p : pls)
  {
System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+p.id);
  }
}

 

 

All Answers

bob_buzzardbob_buzzard

The for loop syntax you are using will only enter the enclosed block of code when there are rows in the list to process.

 

Although you are checking if p is null, this code will only be exercised if there is an element in the list.

 

If you want to test if there are any elements in the list, you'll need something like:

 

 

Id a='001O0000003EcXk';
Id b='a0BO0000000EIBq';

P_L__c pl;

List<P_L__c> pls=[Select Id from P_L__c Where Account__c =:a AND Billing_Period__c=:b];
if (pls.isEmpty())
{
System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&error');
}
else
{
  for(P_L__c p : pls)
  {
System.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+p.id);
  }
}

 

 

This was selected as the best answer
giri rockzzzzgiri rockzzzz

Thank you :):):)