I am using utility class methods which are called in test class to populate all fields of say XYZ object.But i have a field in XYZ object which is formula field. As it is read only i would not want to populate it since it gives me an exception for populating read only field. I tried using below method for DescribeFieldResult object,
public Schema.DisplayType getType()
Though above works if there is no formula field but doesnt work in my case as it depends on the return type(Formula field may have any type Text/Date/Currency). I am a newbie. Hope i will get a better guidance on this. Thanks in advance.
Attribution to: snehakem
Possible Suggestion/Solution #1
You may want something like below:
Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe();
Schema.SObjectType objectType = globalDescribe.get(YOUR_OBJECT_NAME);
Schema.DescribeSObjectResult objectDescribeResult = objectType.getDescribe();
Map<String, Schema.SObjectField> objectFieldMap = objectDescribeResult.fields.getMap();
Schema.SObjectField objectField = objectFieldMap.get(YOUR_FIELD_NAME);
Schema.DescribeFieldResult fieldDescription = objectField.getDescribe();
//Alternatively...
//Schema.DescribeFieldResult fieldDescription = YOUR_OBJECT_NAME.YOUR_FIELD_NAME.getDescribe();
if(!fieldDescription.IsCalculated())
{
// yourObject - this is an instance of YOUR_OBJECT_NAME
yourObject.YOUR_FIELD_NAME = 123;
}
else
{
// do nothing - its a formula field
}
The important part is the DescribeFieldResult object From the docs… IsCalculated - Returns true if the field is a custom formula field, false otherwise. Note that custom formula fields are always read-only.
Schema.DescribeFieldResult Docs Link
Attribution to: Stuart McVicar
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/31960