Skip to content

Instantly share code, notes, and snippets.

@infocynic
Last active February 19, 2025 16:30
Show Gist options
  • Save infocynic/ed1468fa879554897a2427e1f12ada7c to your computer and use it in GitHub Desktop.
Save infocynic/ed1468fa879554897a2427e1f12ada7c to your computer and use it in GitHub Desktop.
Grant View All Fields to a PermissionSet based on a Profile or Pset
//name of Pset to grant access to - must already exist.
final string pSetName = 'ViewAllFieldsAdmin';
//profile takes priority if both are set. can specify same pset as above or a different one.
final string baseProfileForObjectAccess = 'System Administrator';
final string basePermissionSetForObjectAccess = null;
//do not edit below this line
Id pSetToGrantVAFId = [SELECT Id FROM PermissionSet WHERE Name = :pSetName LIMIT 1].Id;
Id pSetForBaseObjectId;
if (baseProfileForObjectAccess != null) {
pSetForBaseObjectId = [SELECT Id FROM PermissionSet WHERE Profile.Name = :baseProfileForObjectAccess LIMIT 1].Id;
} else {
pSetForBaseObjectId = [SELECT Id FROM PermissionSet WHERE Name = :basePermissionSetForObjectAccess LIMIT 1].Id;
}
List<ObjectPermissions> objectPermissionsBase =
[SELECT Id, SObjectType, PermissionsViewAllFields FROM ObjectPermissions
WHERE ParentId = :pSetForBaseObjectId];
boolean isUpsert = pSetForBaseObjectId == pSetToGrantVAFId;
List<ObjectPermissions> objectPermissionsNew;
if (isUpsert) {
objectPermissionsNew = objectPermissionsBase;
} else {
objectPermissionsNew =
[SELECT Id, SObjectType, PermissionsViewAllFields FROM ObjectPermissions
WHERE ParentId = :pSetToGrantVAFId];
}
Map<string, ObjectPermissions> objectNameToPermissionsMap = new Map<string, ObjectPermissions>();
for (ObjectPermissions op : objectPermissionsNew) {
objectNameToPermissionsMap.put(op.SObjectType, op);
}
List<ObjectPermissions> opToUpsertList = new List<ObjectPermissions>();
for (ObjectPermissions op : objectPermissionsBase) {
ObjectPermissions opToUpsert = objectNameToPermissionsMap.get(op.SObjectType);
if (opToUpsert == null) {
opToUpsert = new ObjectPermissions(
ParentId = pSetToGrantVAFId,
SObjectType = op.SObjectType
);
} else if (opToUpsert.PermissionsViewAllFields) {
continue;
}
opToUpsert.PermissionsViewAllFields = true;
opToUpsertList.add(opToUpsert);
}
//some standard objects are weird...
Database.upsert( opToUpsertList, ObjectPermissions.Id, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment