You need to sign in to do that
Don't have an account?
Cast generic sObject without hardcoding object type
I'm writing some code to take an unkonown custom object and create a sharing record for it. I'm able to grab the object name using the DescribeSObjectResult object, work out the sharing object name and then create an instance of it using newSobject and assign it to a sObject. However, when I attempt to add data to the object's fields, I get a "Field expression not allowed for generic SObject" error. Typically, I'd get around this by casting the sObject to the object that I want to use, but, I can't do that here because I don't want to hardcode the object type (this code could be used to provide sharing for a range of records).
Here's the code to quickly get to where I am.
sObject objToShare = new CustomObject__c(); Schema.SObjectType objObjectType; DescribeSObjectResult objDescribeResult; string strObjectName; string strShareObjectName; Map<String, Schema.SObjectType> mapAllSobjects = Schema.getGlobalDescribe(); Sobject objShareRecord; //What object are we dealing with? objObjectType = objToShare.getSObjectType(); system.debug('1*** objObjectType: ' + objObjectType); //Get the name of the object objDescribeResult = objObjectType.getDescribe(); strObjectName = objDescribeResult.getName(); //Get the name of the sharing object associated with it strShareObjectName = strObjectName.substring(0, strObjectName.lastIndexOf('__c')) + '__Share'; system.debug('2*** strShareObjectName: ' + strShareObjectName); //Get an instance of the object objObjectType = mapAllSobjects.get(strShareObjectName); objShareRecord = objObjectType.newSobject(); system.debug('3*** objShareRecord: ' + objShareRecord); //Populate the record objShareRecord.AccessLevel = 'edit'; //!*** ERROR ***!//
I've tried a couple of things to resolve this without any success and I'm sure that this problem must be encountered fairly regularly, does anyone have a way to sucessfully cast the sObject?
I have done the same thing. Here you go..
All Answers
I have done the same thing. Here you go..
So, to sum that one up:
DON'T refer to the field name on the sObject and apply a value, e.g genericObject.yourField = 10;
DO use the put method and use the field name and value as parameters, e.g. genericObject.put('yourField', 10);
Thanks for the super-fast reply!