Create Post Install Script in SalesForce

|
| By Webner

How to create Post Install Script in SalesForce

Definition
A post install script is an Apex class which is executed when a package is installed or upgraded. This class implements the InstallHandler interface. This interface has a method named as onInstall which specifies what is to be performed on installation.

Use
Post install script are commonly used to populate custom settings, create sample data, send an email, notify an external system, or kick off a batch operation to populate a new field across a large set of data or update some existing records. There should be only one apex class which is used to create post install script for the package. A post install script runs after test cases.

InstallContext interface
The onInstall method in the script class takes a context object as its argument whose type is the InstallContext interface. This will be implemented automatically by system when a package is deployed. Context object provides us information about the following variables:

  • organizationId() – This function will return org ID of the organization in which the installation takes place.
  • installerId() – This function will return user ID of the user who initiated the installation.
  • previousVersion() -This function will return version number of the previously installed package. This is always a three-part number, such as 1.1.1.
  • isUpgrade() – This function will return a boolean value whether the installation is an upgrade or not.
  • isPush() – This function will return a boolean value whether the installation is a push or not.

Example of Post install Script

global class PostInstallScript implements InstallHandler {
    global void onInstall(InstallContext context) {
        if (context.previousVersion() != null) {
            // you can call function from class 
            ScriptClass.runScript();
            // or you can code functionality here also
            Account accountRecord = new account(); //Creating account
            accountRecord.Name = 'Webner';
            Insert accountRecord;
        }
    }
}

Example of Test class

@isTest
void Test_PostInstallScript{
PostInstallScript postinstall = new PostInstallScript();
	Test.testInstall(postinstall, null);
	Test.testInstall(postinstall, new Version(1,0), true);
    
	//check the insertion of account record
	Account accRecord = [SELECT id FROM Account WHERE Name= 'Webner' LIMIT 1];
	System.assertNotEquals(accRecord,null);
}

Add Post install script to the package :

1.While editing package detail you have to choose post install script class from look up

2.Select class from Lookup – in this case class name is PostInstallScript

3.After selecting class click on Save.
4.Upload package.
5.When you Deploy this package post install script will run.

Leave a Reply

Your email address will not be published. Required fields are marked *