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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more