function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Paul H 5Paul H 5 

Implement an Apex trigger to enforce field-level security on a custom field based on the User’s profile and User's Role

I tried to implement the above scenarios ,I wanted to know is there any settings in user profile I need to do or this is possible by creating new profile..Help me with the solutions ..Thank you
SwethaSwetha (Salesforce Developers) 
HI Paul,

To enforce field-level security on a custom field based on the User's profile and User's Role in Salesforce, you first need to 
> Create a new Profile or edit an existing Profile that you want to enforce field-level security on.
> In the Profile settings, navigate to the "Field-Level Security" section, find the custom field you want to enforce security on and set the appropriate access level (Read, Edit, or Hidden) for the Profile.
> Apex trigger to enforce field-level security:
trigger FieldLevelSecurityTrigger on CustomObject__c (before insert, before update) {
    for (CustomObject__c record : Trigger.new) {
        // Check field-level security based on user's profile
        if (!Schema.sObjectType.CustomObject__c.fields.CustomField__c.isAccessible()) {
            // Field is not accessible for the user's profile
            record.addError('You do not have access to this field.');
        }
        
        // Check field-level security based on user's role
        if (UserInfo.getProfileId() == 'YourProfileId' && UserInfo.getUserRoleId() == 'YourRoleId') {
            // Additional criteria for user's role
            // Handle enforcement logic here
        }
    }
}
Replace 'YourProfileId' and 'YourRoleId' with the actual Profile Id and Role Id that you want to enforce the field-level security for.

Related:
https://developer.salesforce.com/forums/?id=9060G0000005hnvQAA
https://salesforce.stackexchange.com/questions/164687/class-security-by-user-profile
https://help.salesforce.com/s/articleView?id=sf.code_package_security.htm&type=5

If this information helps, please mark the answer as best. Thank you