[SalesForce] Hierarchy Custom Setting .getInstance() Id

What's the best way to get the Id of the custom setting referenced in MyCustomSetting__c.getInstance() for a hierarchical custom setting?

I'm trying to update your current instance of a custom setting via apex, but can't seem to get the Id (therefore no update possible) from .getInstance().Id. What am I missing?

Best Answer

A few things to take into consideration:

  1. Are you accessing from a test method - If so you must insert a custom setting first
  2. Is there a record for the Specified "Instance" for the current context user?

If no custom setting for the current user is defined then it returns a new custom setting and the ID will be blank. Otherwise the getInstance() should return the ID:

CustomSettingExample__c cs = CustomSettingExample__c.getInstance();

//cd.id - should NOT be null if a custom setting exists for the current context user.

See Custom Settings Methods:

If no custom setting data is defined for the user, this method returns a new custom setting object. The new custom setting object contains an ID set to null and merged fields from higher in the hierarchy. You can add this new custom setting record for the user by using insert or upsert. If no custom setting data is defined in the hierarchy, the returned custom setting has empty fields, except for the SetupOwnerId field which contains the user ID.

If you need more detailed answer then you may be better served by posting your code so we can tell if it is a problem with your code or not.

Related Topic