0

Is it technical feasible to obtain fields like OwnerId, Name from newly inserted record from database.Saveresult?

Apex code:

for(Database.SaveResult sr: srList){
    if (sr.isSuccess()) {
        Id a;
        a = sr.OwnerId
    }
}
2

I don't believe this is possible from Database.saveResult. From the docs, it seems to be used largely as "It worked!/It didn't work!".

// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
    new Account(Name='Account1'),
new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
    // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

As this example demonstrates though and as you say in the question title, you can get the Id using the getId() method of the record and thus to get fields like OwnerId by using this method.

You could simply add the Id to a Set<Id> and query based on that Set<Id> assuming things like the sObject type are persistent.

Set<Id> myAccountSet = new Set<Id>(); // Declare an empty Set

// Do other Database.SaveResult stuff...

if (sr.isSuccess()) { // The same conditional statement as in the for loop before
    myAccountSet.add(sr.getId()); // Add it to the Set created earlier
}

List<Account> myAccountList = [SELECT OwnerId FROM Account WHERE Id IN :myAccountSet]; // Query it!
| 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.