• #17094
    Salesforce | Kumar Kumar #291
    Forcetalks

    Using generic sObject to change fields of different Object types.

    Hi guys,

    I was trying to use the generic ‘sObject’ type to change the name field of any Standard or custom object in my org ( provided it has a field with API name = ‘Name’). I used it as:

    for(sObject a:sobj)
    {
    a.Name = ‘Test’;
    }

    It gives the following error:

    ‘Field expression not allowed for generic SObject’

    Can anyone help me? Thanks

    #17929
    Salesforce | Vikas Kumar Vikas Kumar #292
    Forcetalks

    Hi kumar,

    I know this approach is strange because you are still working with a List<SObject>, but when you assign it you can make it more specific (e.g. List<Account>) by using Type.forName and Type.newInstance methods.

    public static void dynamicUpsert(List<SObject> records)
    {
    Schema.SObjectType sObjectType = records.getSObjectType();
    if (sObjectType != null)
    {
    String listType = ‘List<‘ + sObjectType + ‘>’;
    List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
    castRecords.addAll(records);
    upsert castRecords;
    }
    }

    The getSObjectType call may not be completely reliable, especially since some of these records are being inserted and hence won’t have ids. For that reason, it is probably better to accept sObjectTypeas an additional parameter instead of trying to determine it on the fly.

    public static void dynamicUpsert(List<SObject> records, SObjectType sObjectType)
    {
    String listType = ‘List<‘ + sObjectType + ‘>’;
    List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
    castRecords.addAll(records);
    upsert castRecords;
    }

Viewing 2 posts - 1 through 2 (of 2 total)

Please to reply to this topic.

Popular Salesforce Videos

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

Sending

About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2020 Forcetalks. All Right Reserved.

Log in with your credentials

or    

Forgot your details?