[SalesForce] Sobject put set value of managed field in case of same field api name as unmanaged field

We are developing a managed package that contains a custom object and a REST API to do CRUD operation on that object. We are not using standard salesforce REST API for valid business reasons.

In this REST API we allow user to set value of field on custom object that are part of managed package as well unmanaged field that they may create after package installation. Field that are part of package will be qualified by namespace prefix.

We are facing a issue that may be a platform bug. Here is situation.

  1. Let's assume we have a field with API name FirstName__c and namespace is abc so fully qualified field name will be abc__FirstName__c.
  2. After package installation customer creates another field with same API name(FirstName__c) which is perfectly valid as namespace prefix make them unique.
  3. Through our API user can pass a map of name-value pair, where key is API name of field and value is field value.
  4. Within API we use this map to set value of field by using SObject.put(fieldname, value) method. FieldName is string and value is Object type casted dynamically by checking type of field using describe call.
  5. Problem that we are facing is that if user pass field name as FirstName__c, sObject.put() method sets value of packaged field i.e. abc_FirstName__c not FirstName__c

Best Answer

SObject.put(fieldName, value) 

This method is an overloaded method. It has two definitions:

  • fieldName is of string type
  • fieldName is of Schema.SObjectField type.

The first definition of this method will not work for you but the second definition of this will definitely work for you.

Schema.SObjectField field = Schema.sObjectType.<object_api_name>.fields.getMap().get(<field_api_name);
record.put(field, value);
Related Topic