DEV Community

Anmoldeep Singh Arora
Anmoldeep Singh Arora

Posted on

2

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)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay