Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question
    
Why are you trying to populate the formula field? It's populated at runtime wherever it needs to be. –  highfive Apr 5 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 at 12:51

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer
    
Thank you Stuart. It is exactly what i wanted. –  snehakem Apr 5 at 12:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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