+ Start a Discussion
Sohan ShirodkarSohan Shirodkar 

Enforcing object and field level security in apex

First question is related to checking "Create" permission on object before creating a record of that object. I have referred this  module on Trailhead in which following code snippet is used for checking Create permission.
if (!Schema.sObjectType.Opportunity.fields.Amount.isCreateable()){
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Insufficient Access'));
    return null;
  }
  Opportunity o = new Opportunity(Amount=500);
  insert o;
They have just checked for "Amount" field's create permission which implicitly checks for Opportunity object create permission. But what if we have a long list of fields on Opportunity object which are assigned during object creation. Are we going to check for each one of them in the if statement? It is absolutely unrealistic. How do we implement this check in real world?

Same thing also applies to isAccessible() method. Please recommend me how to implement these checks for a long list of fields in real world scenarios.
 
Adilson Arcoverde JrAdilson Arcoverde Jr
Hi Sohan

Please try this code:
 
Set<String> fieldsToCheck = new Set<String> {
	'Amount',
	'CloseDate',
	'StageName
}

for(String fieldToCheck : fieldsToCheck) {
	if(!Schema.sObjectType.Opportunity.fields.getMap().get(fieldToCheck).getDescribe().isCreateable()) {
		ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Insufficient Access'));
		return null;
	}
}

Opportunity o = new Opportunity(Amount=500);
insert o;

I hope you find this solution helpful. If it does, please mark as Best Answer to help others too.

Regards.