Create Related Records Trigger - smehtaca/vsdk-helloworld GitHub Wiki
This trigger's code is found in the javasdk/src/main/java/com.veeva.vault.custom/triggers/HelloCreateRelatedRecords.java
file. It is the second in the trigger order and is run after inserting a record. This trigger adds two related records if the record that was just created starts with the "Hello, " prefix.
This trigger's main business logic starts from line #15 onwards.
The class annotation (@RecordTriggerInfo) indicates that this class is a record trigger. This annotation specifics the name of the object that the trigger will run on as being that of vsdk_hello_world__c
. Additionally, it specifics that the trigger running on the AFTER_INSERT
event. Lastly it defines that this will be the second trigger run on this object.
To implement the RecordTrigger
interface, the trigger class must have an execute method.
This trigger first creates an instance of the Record Service which will later be used to save our related records.
RecordService recordService = ServiceLocator.locate(RecordService.class);
Next, we use a for each loop to loop over our recordChanges and get the name and id.
for (RecordChange inputRecord : recordTriggerContext.getRecordChanges()) {
List<Record> recordList = VaultCollections.newList();
String recordName = inputRecord.getNew().getValue("name__v", ValueType.STRING);
String recordId = inputRecord.getNew().getValue("id", ValueType.STRING);
Next, if the record name starts with the "Hello" prefix we created the two related record and link them by setting the related_to__c
field with the existing record's id.
// Only create Related To records if there is a record that was found.
if(recordName.startsWith("Hello") && recordId != null) {
Record firstRelatedRecord = recordService.newRecord("vsdk_hello_world__c");
firstRelatedRecord.setValue("name__v", "Related to '" + recordName + "' 1");
firstRelatedRecord.setValue("related_to__c", recordId);
Record secondRelatedRecord = recordService.newRecord("vsdk_hello_world__c");
secondRelatedRecord.setValue("name__v", "Related to '" + recordName + "' 2");
secondRelatedRecord.setValue("related_to__c", recordId);
recordList.add(firstRelatedRecord);
recordList.add(secondRelatedRecord);
}
Finally, we save the records and show error is any occurred.
// List errors.
recordService.batchSaveRecords(recordList).onErrors(batchOperationErrors -> {
batchOperationErrors.stream().findFirst().ifPresent(error -> {
String errMsg = error.getError().getMessage();
int errPosition = error.getInputPosition();
String name = recordList.get(errPosition).getValue("name__v", ValueType.STRING);
throw new RollbackException("OPERATION_NOT_ALLOWED", "Unable to create vSDK records: "
+ name + "related to record " + recordId + "with name: " + recordName + " due to " + errMsg);
});
}).execute();