Search code examples
variablesscopeglobal-variablessalesforceapex-code

Apex - scope - variables



I have tried a lot to get this done but I dont know how to get it working. This is a normal programming question nothing of a Apex/Salesforce riddle.

Scenario: I have a junction object with 2 parent objects for example Lets say there are 3 objects Parent 1, Parent 2 and Junction. When there is only one junction object linked to the Parent1, I am trying to fetch the id of the Parent (This works through the SOQL for me), but when this only One Junction object is deleted; I am trying to save access the ID of the Parent1 when there was 1 Junction object.Note: This all happens inside a for loop which gets iterated everytime you add or delete a junction object!

What I have tried: Pseudocode!

Public static String parent1Id;

for (everytime a junction object is added / deleted)
{

    if (listOfJunctionObjects.size() == 1)
    {
        parent1Id = [Do a SOQL to get the Id from the junction object];
    }

    if (listOfJunctionObjects.size() == 0)
    {
        //CANNOT ACCESS THE parent1Id here
        //The if statements get executed at different times everytime
        the for loop runs
    }
}

What I think is right: I think the parent1Id should be saved in some sort of constant or something so that everytime after the execution of the first if statement the value of parent1Id is the same!

Please help, I really need your help.


Solution

  • I added a field to the Parent1, where I stored the Id of the Parent 1 and then accessed it over multiple iterations.