3

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.

2
  • Why are you trying to populate the formula field? It's populated at runtime wherever it needs to be.
    – highfive
    Apr 5 '14 at 6:55
  • I had made it dynamic. I was populating all fields(by getting field list Sobject.getDescribe().fields.getMap()) and i needed a way to skip formula field. Anyhow @Stuart's code worked for me.
    – snehakem
    Apr 5 '14 at 12:51
5

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.