Salesforce Developer way of granting access to SObject to all profiles

Recently I have described a point-and-clicking way to grant access to SObject to all profiles. It is interesting that there is another way is for Salesforce Developers, which is shorter and concise.

You can just open Developer Console and copy there such code there and then execute it:

public static void grantAccess( String sObjectName ) {
    // Strange but when I try to delete old records it raises internal salesforce error, but it works anyway even if we don't delete the previous records
    //Database.delete( [ select id from ObjectPermissions where Parent.IsOwnedByProfile = true and SobjectType = :sObjectName  ], false );
    List<ObjectPermissions > os = new List<ObjectPermissions >();
    List<PermissionSet> ps = [ select id from PermissionSet where IsOwnedByProfile = true];
    for (PermissionSet p:ps) {
        os.add( new ObjectPermissions(
            ParentId = p.Id, 
            SobjectType = sObjectName,
            PermissionsCreate = true,
            PermissionsDelete = true,
            PermissionsEdit = true,
            PermissionsModifyAllRecords = true,
            PermissionsRead = true,
            PermissionsViewAllRecords = true
    Database.insert(os, false);


Since we can’t detect if Salesforce profile is custom or standard, we need to put second parameter as false to allow partial success in the code.
Also we can use this approach to detect whether Salesforce profile is custom or standard.

This entry was posted in Profile, salesforce, User Management and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s