Activity Forums Salesforce® Discussions Using generic sObject to change fields of different Object types.

  • Using generic sObject to change fields of different Object types.

    Posted by Kumar on December 6, 2016 at 12:39 pm

    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

    Vikas Kumar replied 7 years, 11 months ago 2 Members · 1 Reply
  • 1 Reply
  • Vikas Kumar

    Member
    January 16, 2017 at 7:25 am

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

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos