Skip to content

Instantly share code, notes, and snippets.

@SalesforceBobLightning
Last active March 10, 2021 08:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SalesforceBobLightning/d016b63af206bf0eaa724223366e784c to your computer and use it in GitHub Desktop.
Save SalesforceBobLightning/d016b63af206bf0eaa724223366e784c to your computer and use it in GitHub Desktop.
Generic InvocableMethod for updating a field on an object from Salesforce Process Builder
public class UpdateFieldAction {
@InvocableMethod(
label='Update Field Action'
description = 'Update a field on another object'
)
public static void updateFields(List<Request> requests) {
for(Request request : requests){
updateField(request);
}
}
public static void updateField(Request request) {
String queryString = getQueryString(request.objectName, request.fieldName, request.recordId);
List<sObject> results = Database.query(queryString);
if (results.size() > 0) {
SObject record = results[0];
record.put(request.fieldName, request.fieldValue);
update record;
}
}
private static String getQueryString(String objectName, String fieldName, String recordId) {
List<String> args = new String[]{fieldName, objectName, recordId};
return String.format('SELECT Id, {0} FROM {1} WHERE Id = \'\'{2}\'\'', args);
}
public class Request {
@InvocableVariable(
label = 'Record ID'
description = 'ID of the record to be updated'
required=true
)
public Id recordId;
@InvocableVariable(
label = 'Object Name'
description = 'The name of the object with the field to be updated e.g. Account or Custom_Object__c'
required=true
)
public String objectName;
@InvocableVariable(
label = 'Field Name'
description = 'The name of the field to be updated e.g. Name or Custom_Field__c'
required=true
)
public String fieldName;
@InvocableVariable(
label = 'Value'
description = 'The value to be stored in the field'
required=true
)
public String fieldValue;
}
}
@isTest
public class UpdateFieldActionTests {
@isTest
public static void updateFields_Success(){
// arrange
final String NAME = 'ABCDEFGHIJK';
final String fieldValue = 'lmnopqrstuvwxyz';
Account account = new Account();
account.Name = NAME;
insert account;
UpdateFieldAction.Request request = new UpdateFieldAction.Request();
request.recordId = account.Id;
request.objectName = 'Account';
request.fieldName = 'Name';
request.fieldValue = fieldValue;
// act
UpdateFieldAction.updateFields(new List<UpdateFieldAction.Request> {request});
Account updatedAccount = [SELECT Id, Name FROM Account WHERE Id = :account.Id];
// assert
System.assertEquals(fieldValue, updatedAccount.Name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment