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);
}