Newer Version Available
Version Apex Code Behavior
When subscribers install multiple versions of your package and write code that references Apex classes or triggers in your package, they must select the version that they’re referencing. Within the Apex code that is being referenced in your package, you can conditionally execute different code paths based on the version setting of the calling Apex code that is making the reference. The package version setting of the calling code can be determined within the package code by calling the System.requestVersion method. In this way, package developers can determine the request context and specify different behavior for different versions of the package.
This example uses the System.requestVersion method and instantiates the System.Version class to define different behaviors in an Apex trigger for different package versions.
1trigger oppValidation on Opportunity (before insert, before update) {
2
3 for (Opportunity opp : Trigger.new){
4
5 // Add a new validation to the package
6 // Applies to versions of the managed package greater than 1.0
7 if (System.requestVersion().compareTo(new Version(1,0)) > 0) {
8 if (opp.Probability >= 50 && opp.Description == null) {
9 opp.addError('All deals over 50% require a description');
10 }
11 }
12
13 // Validation applies to all versions of the managed package.
14 if (opp.IsWon == true && opp.LeadSource == null) {
15 opp.addError('A lead source must be provided for all Closed Won deals');
16 }
17 }
18}For a full list of methods that work with package versions, see Version Class and the System.requestVersion method in System Class.
The request context persists if a class in an installed package invokes a method of another class in the package. For example, imagine that a subscriber installs a GeoReports package that contains CountryUtil and ContinentUtil classes. The subscriber creates a GeoReportsEx class and associates it with version 2.3 of the GeoReports package. If GeoReportsEx invokes a ContinentUtil method that internally invokes a CountryUtil method, the request context propagates from ContinentUtil to CountryUtil. Therefore, the System.requestVersion method in CountryUtil returns version 2.3 of the GeoReports package.