0

I need to insert a new ContactShare object in apex. Here is a sample of the code I have :

Map<String, Id> mapUserRole = new Map<String, Id>();
    for(UserRole ur : lRoles){
        mapUserRole.put(ur.Name, ur.Id);
    }
List<ContactShare> lContactShareToInsert = new List<ContactShare>(); 

for(Mission__c mission : lMissions){
    for(Contact con : lContacts){
                    if(mission.box__c != con.box__c && mapUserRole.get(mission.box__c) != null){

                        //créer contactShare
                        ContactShare conShare = new ContactShare();
                        conShare.ContactAccessLevel = 'Read';
                        conShare.ContactId = con.Id; 
                        conShare.UserOrGroupId =  mapUserRole.get(mission.box__c);

                        System.debug('### conShare : ' + conShare);

                        lContactShareToInsert.add(conShare);

                        System.debug('### lContactShareToInsert : ' + lContactShareToInsert);
                    }
                }
             }

 Database.SaveResult[] srContactShare = Database.insert(lContactShareToInsert, false);

    for(Database.SaveResult srS : srContactShare){
        System.debug('### srS : ' + srS);
        if(srS.isSuccess()){
            System.debug('### srContactShare is insert');
        }
    }

The problem is that I got an error in the debug of srS, so the list of contactShare to insert is not insert because it is not successfill :

srS : Database.SaveResult[getErrors=(Database.Error[getFields=(UserOrGroupId);getMessage=User/Group ID: id value of incorrect type: 00E4E000000Xfj4UAC;getStatusCode=FIELD_INTEGRITY_EXCEPTION;]);getId=null;isSuccess=false;]

1
  • Make your apex class "without sharing" and then try!
    – Ayub
    May 18 '18 at 9:03
3

Based on the User, Sharing, and Permission Objects ERD copied below, you will have to identify a single User object that references a selected UserRole and use the Id of that in conShare.UserOrGroupId.

enter image description here

0
1

Refer Sharing a Record Using Apex

UserOrGroupId should be either userId or public group id.

According to your code, it is UserRoleId, thats why it is invalid value.

You can create a public group based on the role and use that public group id for sharing the record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.