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
Claire CrabtreeClaire Crabtree 

Querying PermissionsEdit for a Field on Profiles

I am using the following script to check which profiles have Edit Permissions for specific fields. For some reason, it is only returning a few profiles, where I was expecting all of them. Will there only be a FieldPermissions record if the profile does not have "No Access" to the object?
String obname = 'Account';
String myfieldname = 'Name';
Boolean isField = false;
Integer falsecount = 0;

Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(obname).getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values()){
    schema.DescribeFieldResult dfield = sfield.getDescribe();
    if(String.valueOf(dfield.getname()).containsIgnoreCase(myfieldname)){
        System.debug(myfieldname + ' is a field on ' + obname);
        isField = true;
    }
}

IF(isField == true){
    String myquery = 'select field, PermissionsEdit, PermissionsRead, parentid, parent.isownedbyprofile, parent.profileid, parent.profile.name from fieldpermissions where sobjecttype = \'' + obname + '\' AND field = \'' + obname + '.' + myfieldname + '\' AND parent.profileid != \'\'';                                       
    List<FieldPermissions> objectField = Database.query(myquery); 
    System.debug('size of list: ' + objectField.size());
    for(FieldPermissions fp : objectField){
        System.debug(fp.parent.profile.name + ' profile, edit: ' + fp.permissionsedit);
        if(fp.permissionsedit == false){
            System.debug(fp.parent.profile.name + ' profile, edit: ' + fp.permissionsedit);     
        falsecount += 1;
        }
    }
    if(falsecount == 0){
        System.debug('There are no profiles that do not have edit access to the field ' + myfieldname );
    }
}
else{
    System.debug(myfieldname  + ' is not a field on ' + obname);
}