5

Is it possible to check if the previous version is: "Less than" a certain value using the context.previousVersion() field.

The documentation does a one-to-one comparison for a specific version like so:

if(context.previousVersion().compareTo(new Version(1,0)) == 0)

So could I check for versions less than 1.0?

8

I'm not sure about the PostInstall context, but looking at the documentation for Version.compareTo() I'd say it was possible.

Try something like:

if(context.previousVersion().compareTo(new Version(1,0)) < 0) {
    // Previous Version is Less than Version 1.0 code
}

Updated docs:

Return Value
Type: Integer
Returns one of the following values:

  • zero if the current package version is equal to the specified package version
  • an Integer value greater than zero if the current package version is greater than the specified package version
  • an Integer value less than zero if the current package version is less than the specified package version
| improve this answer | |
  • 1
    Your right, it's not documented, but actually that method returns a number -1 if the version is less than the version given, and a 1 if it's greater. – jordan.baucke Dec 5 '12 at 23:56
  • 2
    Late to the party, but I wanted to comment to link to the documentation, that now includes the correct return values of compareTo() : developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… – David Apr 10 '17 at 21:16
2

You can also use major() and minor() methods in the Version object to get each part of the version number:

The version number has the format majorNumber.minorNumber.patchNumber (for example, 1.2.0)

if ((context.previousVersion().major() == 1) 
     && (context.previousVersion().minor() > 0)
     && (System.requestVersion().minor() <=9))
{
    // Do something for versions  between 1.1 and 1.9
}
else if (context.previousVersion().compareTo(new Version(2,0)) >= 0)
{
    // Do something completely different for versions 2.0 or greater
}

Source: Salesforce Version Class

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.