[Salesforce]Dml操作で成功したレコード取得

Dml操作で成功したレコード取得した例を共有します。

list<RecordType> rList = [Select id 
                                        From RecordType 
                                        Where sObjectType = 'Account' and DeveloperName = 'PersonAccount'];

system.debug('rList:'+rList);

List<Account> accs = new List<Account>();
for(integer i=0; i<10; i++){
    Account acc = new Account();
    acc.LastName = 'test' + i;
    acc.RecordTypeId = rList.get(0).id;
   accs.add(acc);
    system.debug('acc:'+acc);
}
insert accs;

List<SObject> accList = new List<SObject>();
accList = [select id, LastName From Account];
if(accList.size() > 0){
    system.debug('accList.size():'+accList.size());
    Set<Id> updatedIds = new Set<Id>();
    List<SObject> updatedObjs = new List<SObject>();
    Database.SaveResult[] srList = Database.update(accList, false);
    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());
            updatedIds.add(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());
            }
        }
    }
    if(updatedIds.size() > 0){
        for(SObject obj : accList){
            if(updatedIds.contains(obj.Id)){
                System.debug('obj.Id:'+obj.Id);
                updatedObjs.add(obj);
            }
        }
    }

}

投稿者: kinkun

保有資格 Salesforce Certified Platform App Builder T Salesforce Certified Platform Developer I Salesforce Certified Platform Developer II Salesforce Certified Administrator

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です