Friday, June 3, 2011

Update a Salesforce Custom Setting from Apex

I needed to update a Salesforce Custom Setting in a test method to check various use cases from code. Looking at the Custom Settings Methods documentation doesn't show methods for updating a custom setting instance.

I checked the partner API and the custom setting shows up as a custom object that can be updated using standard Data Manipulation Language (DML) statements.

So if the Custom Setting Definition had the Name as "Config" then it could be updated as follows:

     Config__c configEntry = [Select Id, TextValue__c From Config__c Where Name = 'A Config Name'];
     configEntry.TextValue__c = 'China, Australia, France';
     update configEntry;

Oddly, this works fine when the tests are run via Eclipse but when run from within Salesforce I get an error like:

System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: Config__c

To resolve this wrap the previous code in a System.runAs(user) call as follows:

     User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
     System.runAs ( thisUser ) {
          Config__c configEntry = [Select Id, TextValue__c From Config__c Where Name = 'A Config Name'];
          configEntry.TextValue__c = 'China, Australia, France';
          update configEntry;
     }

See also: