0

I had to transfer a bunch of records from one user to another today. I decided to use the dev console because I needed it done quickly.

I wanted to write generic code using sObjects but couldn't work through it, so I ended up hard-coding the SObjectType and powering through it.

Now I'm trying to figure out how to write some generic code where I can specify sObjectType, newOwnerId and currentOwnerId and the code will update the OwnerId on each record from currentOwnerId to newOwnerId.

So far I've been able to query the records into a list, and cast that list to the specified sObject type (using the approach in this post). I'm stuck on how to work with the OwnerId field in the list of cast records in a for loop. Here's what I've tried:

string sObjType = 'Contact';
id currentOwner = '00540000001CtuIAAS'; 
id newOwner = '005400000038FL2AAM';
string listType = 'List<' + sObjType + '>';

list<sObject> sObjList = Database.query('SELECT Id,OwnerId from ' + sObjType +' Where OwnerId =: currentOwner');

list<sObject> sObjUpdate = new list<sObject>(); //will hold the records to update

list<sObject> castRecords = (List<Sobject>)Type.forName(listType).newInstance();
castRecords.addAll(sobjList);

for (sObjType s : castRecords){
    s.OwnerId = newOwner;
    SObjUpdate.add(s);
}

1 Answer 1

2

You're making this implementation overly complicated. You don't need to cast the list at all.

public static void transfer(SObjectType sObjectType, Id formerOwnerId, Id newOwnerId)
{
    List<SObject> records = Database.query('SELECT Id FROM ' + sObjectType + ' WHERE OwnerId = :formerOwnerId');
    for (SObject record : records) record.put('OwnerId', newOwnerId);
    try
    {
        update records;
    }
    catch (DmlException d)
    {
        // handle your DML Exceptions!
    }
}
1
  • worked perfectly. i could not figure out how to construct a sObjectType record to pass into the method, so I switched it to a string --> public static void transfer(string sObjType, Id formerOwnerId, Id newOwnerId) and that worked fine
    – gorav
    Dec 21, 2016 at 19:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .