1

I'm new in Apex and I'm trying build a Hierarchy Tree with 4 objects: Account, Carteira__c, Produtos_das_carteiras__r and AtivosFundo__c

One Account can have N Carteira__c

One Carteira__c can have N Produtos_das_carteiras__r

One Produtos_das_carteiras__r can have N AtivosFundo__c

I wrote the code below as my Controller, but the following error is appearing: 'Variable does not exist: tempativos'

Can someone help me, please?

Public with sharing class TreeDetalhes {
Private final Account acct;
Public TreeDetalhes(ApexPages.StandardController stdController) {
    this.acct = (Account)stdController.getRecord();
    }

Class cNodes {
Public Account gparent {get;set;}
Public List<Carteira__c> parent {get; set;}
Public List<AtivosFundo__c> gchildren {get; set;}

Public cNodes(Account gp, List<Carteira__c> p, List<AtivosFundo__c> gc)
{
 gparent = gp;
 parent = p;
 gchildren = gc;
}
}

Public List<cNodes> hierarchy;

Public List<cNodes> getmainnodes()
{
    hierarchy = new List<cNodes>();
    List<Account> tempparent = [Select Id,Name from Account where id = :acct.Id];
    for (Integer i =0; i< tempparent.size() ; i++)
    {
        List<Carteira__c> tempchildren = [Select Id,Name,(Select Id,Aloc__c, Fundos__r.Name, Fundos__c from Produtos_das_carteiras__r r) from Carteira__c where Integrante__c = :tempparent[i].Id];
        for (Carteira__c c : tempchildren) {
            for (AtivosCarteira__c ac : c.Produtos_das_carteiras__r) {
                List<AtivosFundo__c> tempativos = [Select Id, FundoRelacionado__r.Name From AtivosFundo__c where Fundos__c = :ac.Fundos__c];
            }
        }
    hierarchy.add(new cNodes(tempparent[i],tempchildren,tempativos));
    }   
    return hierarchy;
}   
        }
2

You're declaring tempativos within the scope of the for loop.

You'll need to declare it at the same location as the tempchildren variable.

e.g.

List<Carteira__c> tempchildren = [Select Id,Name,(Select Id,Aloc__c, Fundos__r.Name, Fundos__c from Produtos_das_carteiras__r r) from Carteira__c where Integrante__c = :tempparent[i].Id];
List<AtivosFundo__c> tempativos;
    for (Carteira__c c : tempchildren) {
        for (AtivosCarteira__c ac : c.Produtos_das_carteiras__r) {
            tempativos = [Select Id, FundoRelacionado__r.Name From AtivosFundo__c where Fundos__c = :ac.Fundos__c];
        }
    }
hierarchy.add(new cNodes(tempparent[i],tempchildren,tempativos));

Keep in mind that you're performing a SOQL query within a for loop, which is a really bad practice. You should look into how to bulkify your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.