Search This Blog

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




Once the field is retrieved the describe information of this field can be queried and based on that, validations or conversions to the required type or conditions like enabled/disabled/updateable can be checked.

objectToUpdate.put(fieldToUpdate, fieldValue);

Values for formula fields cannot be set using dynamic SOQL. This is because they are set while the value is retrieved either through display or through queries.

This is all fine if the field is normal like text, time, picklist or double etc. But what if you want to retrieve or set information about a Look up object.

Example. In a tutorial, a student is trying to add his educational history to the portal but his college is not listed. He is given an option to add a new college name. When he saves the data, we have to create a new college in our records and link that to this student. Here, comes the use of the child relationship.

This is very simple. First create an Sobject for the college type, update it with all the required values like name, city... and add that sobject to the actual student.

schema.SObjectType targetType = Schema.getGlobalDescribe().get('testnsp__college__c');
sobject collegeObj = targetType.newSObject();
collegeObj.put('name', 'collegeName');
---
Database.insert(collegeObj);
student.putSObject('testnsp__college__r', collegeObj);


No comments:

Post a Comment