+ Start a Discussion

Issue with the LOOP


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>();
            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));
                    for(Account accChild:acc.childAccounts){
        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.



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