Although the onInsertBefore method can be overridden to implement logic to set default values on record insert, the following code, added to the Contestants Domain class, has chosen to override the onApplyDefaults method instead. This was used as it is more explicit and permits a Separation of Concerns between the defaulting code and the record insert code, although both are fired during the insert phase:
public override void onApplyDefaults() { for(Driver__c driver : (List<Driver__c>) Records) { if(driver.ShortName__c == null) { // Upper case first three letters of drivers last name String lastName = driver.Name.substringAfterLast(' '); driver.ShortName__c = lastName.left(3).toUpperCase(); } } }
The preceding code attempts to populate the driver short name, which is typically made up of the first three characters of their second name in uppercase, so Lewis Hamilton will become HAM.