function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PawanKumarPawanKumar 

How to put field level security(FLS) check for Formula field in Apex?

Hi All,
I have a field level security requirement around custom formula. If the user does not have read access for the custom formula field at the profile level, User should not be abe to see the value at all in the custom Lightning component page / VF page but whenever i do security check in apex code for the field and assign any value to it then it is throwing error saying "formula fields are not writeable".

Please take a snap of my code as below:

List<hed__Course_Offering__c> courseOfferingList = [Select Id,Course_ID__c from hed__Course_Offering__c where hed__Term__c IN :termList ];
for(Integer i=0; i<spProgramDetail.courseOfferingList.size();i++){
// Course_ID__c is a FORMULA Field.    
 if (!Schema.sObjectType.hed__Course_Offering__c.fields.Course_ID__c.isAccessible()){
    courseOfferingList[i].Course_ID__c = '';
    }
}

Any help would be appreciated.

Regards,
Pawan Kumar
kaustav goswamikaustav goswami
Formula fields by definition are read only. You cannot assign any value to a formula field. You are attempiting to do an illegal assignment in this staement of your code - courseOfferingList[i].Course_ID__c = '';

You can only use formula fields to derive values based on values of other fields. 
it is read only and cannot be assigned a value in code or anywhere else.

Thanks,
Kaustav
Prachi SPrachi S
Hi Pawan,
If you want to hide a field from VF page based on FLS or CRUD access to the logged in user all you have to do is refer the SObjects and SObject fields directly in the VisualForce page; in your case Course_ID__c. VisualForce will remove fields for which users do not have FLS visibility when rendering edit pages. The same is also true for lightning component page.

Refer Automatic CRUD and FLS Enforcement in VisualForce section in  https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS 

And you cannot assign a value to formula field in Apex as formula fields are read only.