Solution to common Apex issue - ApexCRUDViolation.

eduanmoldeep

Anmoldeep Singh Arora

Posted on February 2, 2023

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

💖 💪 🙅 🚩
eduanmoldeep
Anmoldeep Singh Arora

Posted on February 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related