function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aaron Persich 9Aaron Persich 9 

Random number with Apex

Hello,

I am fairly junior to Apex and I am tgrying to build a random number.  I found this Apex code online and saved it successfully in my Sandbox.  
public with sharing class RandomNumberGenerator {
    public static String generateRandomNumber() {
        String randomNumber = generate();
        if (randomNumber.length() < 6) {
            String randomNumber2 = generate();
            randomNumber = randomNumber + randomNumber2.substring(0, 10 - randomNumber.length());
        }
        return randomNumber;
    }
    public static String generateIdentifier(String prefix) {
        return prefix + '-' + generateRandomNumber();
    }
    private static String generate() {
        return String.valueOf(Math.abs(Crypto.getRandomInteger()));
    }
}
I have a number field labeled BIOS_Password__c on the asset object.  How do I get this Apex class to populate this field on creation of the asset?  Any help is much appreciated.

Thanks,

Aaron
 
bob_buzzardbob_buzzard
You'll need to put it into a trigger.  Something like:
 
trigger AddBIOSPassword on Asset (before insert) 
{
    for (Asset ast : Trigger.new) {
        ast.BIOS_Password__c=RandomNumberGenerator.generateRandomNumber();
    }
}