Creating Records With SMQL
To create a new record, use the Record.newRecord method. This method receives the full identifier of the object to which you want to add a record. You then insert the record with the Database.insert method:
def newRecord = Record.newRecord("io_basic_object_for_test")
newRecord.io_owner = UUID.randomUUID() //this should be a reference to an existent user, using random id here so it can be tested easily
newRecord.io_name = "a name"
Database.insert(newRecord)
You can insert multiple records with a single call to Database.insert by passing a collection of records instead of just one record:
def newRecords = [
Record.newRecord("io_basic_object_for_test"),
Record.newRecord("io_basic_object_for_test")
]
newRecords[0].io_owner = UUID.randomUUID()
newRecords[0].io_name = "a name"
newRecords[1].io_owner = UUID.randomUUID()
newRecords[1].io_name = "a name"
Database.insert(newRecords)
By default, validation is not executed at the Groovy level, but is executed before the record is inserted into the database:
def newRecord = Record.newRecord("io_basic_object_for_test")
newRecord.io_owner = UUID.randomUUID()
Database.insert(newRecord) // This will run OK, but an error will be produced when the record is committed to the database
For immediate validation, you can display an error code or throw an exception. For example, to throw a DmlException exception when validation errors occur:
def newRecord = Record.newRecord("io_basic_object_for_test")
newRecord.io_owner = UUID.randomUUID()
try {
Database.insert(newRecord,Database.ValidationMode.ThrowExceptionOnValidationError)
} catch(DmlException e) {
e.getNumDml(); // Number of errors
e.getDmlMessage(0); //Message for the Nth error
}
To get a result for each record saved instead of an exception:
def newRecords = [
Record.newRecord("io_basic_object_for_test"),
Record.newRecord("io_basic_object_for_test")
]
newRecords[0].io_owner = UUID.randomUUID()
newRecords[1].io_owner = UUID.randomUUID()
newRecords[1].io_name = "a name"
SaveResult[] results = Database.insert(newRecords, Database.ValidationMode.ReturnErrorOnValidationError)
results.size(); // one result for each record (independently of sucess/error)
results[0].isSuccess(); // true if the record was valid
results[0].getErrors().size(); // number of errors for the first record
results[0].getErrors()[0].getMessage(); // error message for the Nth error
For more information:
Was this helpful?