DEV Community

Anmoldeep Singh Arora
Anmoldeep Singh Arora

Posted on

Solution to common Apex issue - ApexCRUDViolation.

The simple answer is to put an if statements that ensures we have access at runtime, and instruct our SOQL Queries to respect the rules set by Admin.

Eg:

if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
  // Create new contact
}

Or for SOQL Queries, you can add WITH SECURITY_ENFORCED to tell apex that while fetching records do respect the policies set by the Org Admin.

Eg:

List<Account> act1 = [SELECT Id, (SELECT LastName FROM Contacts)
  FROM Account WHERE Name like 'Acme' WITH SECURITY_ENFORCED]

Pretty Common to forget, but can save hours of Fixing PMD Issues Later on!

Have a good day :)

For Details check:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_perms_enforcing.htm

Top comments (0)