[SalesForce] Possible to use runAs in Apex Trigger
Is it possible to use system.runAs() methods in a trigger? If it possible please provide sample code.
Best Answer
This method can only be used in tests. You can find the documentation for System.runAshere. Its documentation says:
All of the specified user's record sharing is enforced during the execution of runAs. You can only use runAs in a test method. For more information, see Using the runAs Method.
Instead of calling a single @future(callout=true) method you can start a batchable running where the number of records processed in each execute call can be limited to be below the governor limit:
public class Plexure {
public static void PushMessage(Set<Id> pushMessageIds) {
Database.executeBatch(new MyBatchable(pushMessageIds), 50);
}
}
A batchable breaks work for many records up into multiple limited size lists of records. Your TMP_Push_Messages__c query goes into the start method and the rest of the code goes into the execute method.
You also need to add the Database.AllowsCallouts marker interface:
public class MyBatchable implements Database.Batchable<sObject>, Database.AllowsCallouts {
private Set<Id> pushMessageIds;
public MyBatchable(Set<Id> pushMessageIds) {
this.pushMessageIds = Set<Id> pushMessageIds;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
select consumerId__c, messageId__c
from TMP_Push_Messages__c
where Id IN :pushMessageIds
]);
}
public void execute(Database.BatchableContext bc, List<TMP_Push_Messages__c> scope) {
...
}
public void finish(Database.BatchableContext bc) {
}
}
Best Answer
This method can only be used in tests. You can find the documentation for
System.runAs
here. Its documentation says: