Search This Blog

Showing posts with label SOQL. Show all posts
Showing posts with label SOQL. Show all posts

Friday, August 16, 2013

Dynamic SOQL for setting fields or relationships

In apex, objects can be created and manipulated dynamically. The only thing that needs to be known is Object Name.

Salesforce maintains a static object called 'Schema'. This will contain information about all the objects in the org in a map format. If the object is a standard object, the key will be just it's name. For custom objects, they are maintained under key as 'NamespacePrefix__'+'Object Name'+'__c'. For example, if the namespace is nspTest and the object name is Tester, then the key will be 'nspTest__Tester__c'. This complete name is called as API name.

Every Object in salesforce is inherited from "sObject" and is related to a schema. The information about the object is called "describe". It includes the fields related to this objects, child relationships like the lookup's master-childs etc.... If the field it custom field, the name will have '__c' suffix.

Schema.SObjectType targetType = Schema.getGlobalDescribe().get(sObjName);
Map fieldMap = targetType.getDescribe().fields.getMap();
Schema.SObjectField sField = fieldMap.get(fieldToUpdate);