FLS Check in Apex Class

In an apex class you should check Field Level Security. Most of us do not check. This is best practice to explicitly check security before any database statement like SELECT, INSERT, UPDATE AND DELETE. If you create an app to for AppeExchange then it is must for your app. For example if a user have access to read all contact but not able to create or modify record. So you also have to check is logged in user able to create or update record in your apex class.

Learning FLS in apex class by steps

1. Check for Object is accessible or not means if you want to get account name and phone. Then your should be like

if(Schema.SObjectType.Account.isAccessible()) // Object Accessibility 
{
   //Fields Accessibility
   if(Schema.SObjectType.Account.Fields.Name.isAccessible() && Schema.SObjectType.Account.Fields.Phone.isAccessible())
   {
        List<Account> accList = [Select Name,Phone from Account Limit 1];
   }
}

2. Check create permission if you want to insert account record.

if(Schema.SObjectType.Account.isCreateable()) // Object Accessibility 
{ 
    //Fields Accessibility 
    if(Schema.SObjectType.Account.Fields.Name.isCreateable() && Schema.SObjectType.Account.Fields.Phone.isCreateable()) 
    { 
          Account accObj = new Account(Name='Test',Phone='1234567890');
    } 
}

NOTE 1: Do not write SOQL query without LIMIT or Where Clause.
In your SOQL query write where clause like [Select id from contact where name =’test’].
[Select id from contact LIMIT 1];

Leave a Reply

Your email address will not be published. Required fields are marked *