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
Ravi_SFDCRavi_SFDC 

Issue with the LOOP

Hi,

I am trying to get the list of accounts, under the Hierarchy. (example I am the contact of an account AAA, and I am the parent account for X1, X2, and X3 accounts whose status is Active, Partner Account is TRUE, and Record. Type is CC.)  
 

User u = [SELECT Contact.AccountId FROM User WHERE Id = :UserInfo.getUserId() WITH SECURITY_ENFORCED];
        String accountId = u.Contact.AccountId;
        Set<Id> accIds = new Set<Id>{accountId};
        List<Account> accounts = new List<Account>();
        while(!accIds.isEmpty()){
            List<Account> accList = [Select Id, Name, ParentId, CenterCode__c, (Select Id, Name, ParentId FROM ChildAccounts) FROM Account Where 
            Status__c = 'Active' and
            IsPartner = true and
            RecordType.Name = 'Community Account' AND Id IN :accIds ORDER By Name];
            accIds = new Set<Id>();
            for(Account acc:accList){
                accounts.add(new Account(Id = acc.Id, Name = acc.Name, CenterCode__c = acc.CenterCode__c, ParentId = accountId == acc.Id ? null : acc.ParentId));
                if(!acc.childAccounts.isEmpty())
                    for(Account accChild:acc.childAccounts){
                        accIds.add(accChild.Id);
                    }
            }
        }
        return accounts;

1. I am using the WHILE condition to get into the loop, and this is running number of times.

2. If I am using if condition, the loop is running only one time, but i am not getting the list of accounts on the UI.

Your help would be really appreciated.

Thanks
Ravi.

 

prateek khanna 24prateek khanna 24
Avoid soql query inside loops, it will hit the governer limit.