0

I have a static variable that would hold a Map with Ids and relevant custom objects. The map is initialized by a simple function (some SOQL calls and List to Map transform):

public static Map<String, CustomObject__c> myMap = getMyMap()

Later, in my Apex controller I could easily use myMap anywhere and get CustomObject's field from the map using a function like this:

@AuraEnabled
public static String loadName(String objectId) {
    return myMap.get(objectId).Name;
}   

The problem is that now the requirements have changed and I need to pass an argument to getMyMap function to make it look like getMyMap(String otherId). I need to pass this otherId argument from JS Helper.

I wanted to created myMap variable like this: public static Map<String, CustomObject__c> myMap and add an init function that would initalize myMap and would be called from JS Helper:

@AuraEnabled
public static Map<String, FeatureType__c> initializeMap(String otherId) {
    List<CustomObject__c> objectList = getListSomehow(otherId);
    Map<String, CustomObject__c> customObjectMap = new Map<String, CustomObject__c>();

    for(CustomObject__c object: objectList){
      customObjectMap.put(object.Id, object);
    }

    //Here I wanted to set my static variable myMap
    myMap = customObjectMap;

    return customObjectMap;
}

I thought that would work but it seems that myMap variable is not initalized as I get an error: System.NullPointerException: Attempt to de-reference a null object.

I need to use this static variable in many places in my Apex Controller so I am looking for a way to initialize it once at the beginning using provided String argument passed from the JS Helper.

Is it possible?

1

1 Answer 1

4

Scope of a Static variable is per transaction.

initializeMap is 1 transaction, loadName is another transaction.

The values you set in 1st transaction, won't be retrievable by the second transaction.

Anywho AuraEnabled are stateless methods, ie you are never supposed to get state from any other class level context variable unless you initizale them in your context.

I would keep it simple and delay the SOQL till the last moment. So removing initializeMap and just doing your operation/SOQL in loadName sounds more appropriate.

Not the answer you're looking for? Browse other questions tagged .