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
Brendan MBrendan M 

Field integrity exception when attempting to insert field permissions to profiles

Hi Community! 

Currently trying to add a field permission to multiple Profiles to save me some time in the future. Have included the error and code below. Any ideas what I'm doing wrong? Or has anyone done this before? 

I'm sure it worked on permission sets. Anyways appreciate any help! Thanks 

Currently getting the error:

Line: 19, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Parent ID: id value of incorrect type: 00e2P000000LtXfQAK: [ParentId]

From: 
// Create a Map of Profiles to update. 
Map<Id, Profile> profileMap = new Map<Id, Profile>([SELECT Id, Name FROM Profile WHERE Name LIKE 'Service%' OR Name LIKE 'API%' OR Name LIKE 'System%']);
// Create List of Field Permissions to add. 
FieldPermissions[] fieldPermissionsToInsert = new List<FieldPermissions>(); 

// Loop through and create Field Permissions. 
For(Id i : profileMap.keyset()) {
  FieldPermissions fp = new FieldPermissions();
  fp.Field ='Package__c.AvailableBalance__c';//the name of new field
  fp.ParentId = i; // Get the Id of the Parent - Permission set or profile.  
  fp.PermissionsEdit=false;//
  fp.PermissionsRead=true;
  fp.SobjectType='Package__c';
  fieldpermissionsToInsert.add(fp);
}

// Insert Field Permissions. 
if(fieldPermissionsToInsert.size() > 0) {
    insert fieldPermissionsToInsert;
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

The Parentid refers to the Lookup only to the Permission set but nit for the Profile I guess.  Here profileMap is the map of Profiles because of which you are facing the error.

Please find the object reference (https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_fieldpermissions.htm) for Field permissions object where it was mentioned.

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,