Passing objects to future methods

Future methods are used to run a code in a separate thread at a later time when system resources are available. We can use them to run something asynchronously, for example make a web service callout from an Apex Trigger. This way we can make sure user does not wait for response to get back. Future methods must be static and if you want to make callouts annotation needs to include (callout=true):

<pre class="wp-block-syntaxhighlighter-code">
@future (callout=true)
public static void doCallout() {
    //make callout here
}
</pre>

Future methods does not allow passing objects as an arguments, only primitive data types are accepted, however we can oversome this limitation by using serialization and deserialization. Here is how we can do this:

OpportunityTrigger

<pre class="wp-block-syntaxhighlighter-code">
Trigger OpportunityTrigger on Opportunity( after insert) {
     String jsonString = json.serialize(Trigger.NEW);

     OpportunityTriggerHandler.process(jsonString);
}
</pre>

OpportunityTriggerHandler

<pre class="wp-block-syntaxhighlighter-code">
public class OpportunityTriggerHandler {
    @future(callout=true)
    public static void process( String jsonString) {
          List&amp;lt;Opportunity&gt; oppNewtList = (List&amp;lt;Opportunity&gt;)Json.deserialize(jsonString, List&amp;lt;Opportunity&gt;.class);
    }
}
</pre>

Adding users to permission set through Apex

Here is how we can add/remove a user to/from a permission set through Apex. My requirement was to add or remove a user from a permission set when the value of a checkbox changes in user object.So I have this code in User Update After trigger.

Here is the code to add to a PermissionSet:

Here is the code to remove from a PermissionSet: