[SalesForce] DML Operation on List – Where I got the record ID of various objects

Scenario: I got a VF Page where I will get only ID's of various Objects, I wouldn't know which Object RecordID I would be getting in an instance. I need to update that record with that ID. Without knowing which Object, I can't create an instance of that object to update.

I need to update that list, where Objects could be of any type Accounts, Contacts Or any Custom Object.

Please advise, How can I achieve this.

Best Answer

You can instantiate an sObject record from an Id without knowing its type.

SObject record = someId.getSObjectType().newInstance(someId);

As already mentioned by Tushar, you can mix types in your operation, up to 10 types. You could do something like the following to flexibly support an arbitrary number of objects. It's just a sketch of what you need to implement; obviously you will have to test it and tweak to suit your needs. You may want to add some governor protections and other safeguards.

public dynamicUpdate(Set<Id> recordIds)
{
    Map<SObjectType, Set<Id>> objects = new Map<SObjectType, Set<Id>>();
    for (Id recordId : recordIds)
    {
        SObjectType idType = recordId.getSObjectType();
        if (!objects.contains(idType))
            objects.put(idType, new Set<Id>());
        objects.get(idType).add(recordId);
    }

    Integer typeCount = 0;
    List<SObject> records = new List<SObject>();
    for (SObjectType sObjectType : objects)
    {
        typeCount++
        for (Id recordId : objects.get(sObjectType))
            records.add(recordId.getSObjectType().newInstance(recordId));
        if (typeCount == 10)
        {
            update records;
            records.clear();
            typeCount = 0;
        }
    }
}
Related Topic