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
SFDC Admin 56SFDC Admin 56 

caused by: System.DmlException: Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [UserOrGroupId]: [UserOrGroupId]

I am trying to update Premier rep new fiel from dataloader and some records are updating but on some its giving me two types of error.

1) caused by: System.DmlException: Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [UserOrGroupId]: [UserOrGroupId]

2)Sharingupdatepremier: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: [] 

I have tried every condition and unable to figure out, any input is appereciated.

trigger Sharingupdatepremier on Account (before update) 
{
 Legal_Doc__Share PrimarysalesrepShr = new Legal_Doc__Share();

    if(trigger.isUpdate)
    {
        Set<Id> setAcc = new Set<Id>();
        Set<String> setPrimSal= new Set<String>();
        for (Account a : Trigger.old )
        {
            setAcc.add(a.id);
            setPrimSal.add(a.Premier_Rep2__c);
        }
        
        List<Legal_Doc__c> legaldocu = [Select id From Legal_Doc__c where Accounts__c in : setAcc];
        List<Legal_Doc__Share> legdoc = [Select UserOrGroupId From Legal_Doc__Share Where UserOrGroupId in :setPrimSal and ParentId = :legaldocu and  RowCause = 'Manual' ];
    
        if(!legdoc.isEmpty())
        {
            Delete legdoc;
        }
    } 
        
    List<Legal_Doc__Share> ListPrimarysalesrepShr = new List<Legal_Doc__Share>();
                
    Set<ID> setAccId = new Set<Id>();
    for (Account an : Trigger.new )
    {
        setAccId.add(an.id);
    }
    List<Legal_Doc__c> Listlegaldocum = [Select id,Accounts__c From Legal_Doc__c where Accounts__c in :setAccId];
    Map<Id,Legal_Doc__c> mapAccWiseLegalIDoc = new Map<Id,Legal_Doc__c>();           
    for(Legal_Doc__c leg : Listlegaldocum)
    {
        mapAccWiseLegalIDoc.put(leg.Accounts__c,leg);
    }
    
    for (Account an : Trigger.new )
    {
        
        If(mapAccWiseLegalIDoc.containsKey(an.Id))
        {
            PrimarysalesrepShr = new Legal_Doc__Share();
           
            PrimarysalesrepShr.ParentId = mapAccWiseLegalIDoc.get(an.Id).Id;
            PrimarysalesrepShr.UserOrGroupId = an.Premier_Rep2__c;
            PrimarysalesrepShr.AccessLevel = 'edit';
            
            ListPrimarysalesrepShr.add(PrimarysalesrepShr);
        }
    }
    if (Account.Premier_Rep2__c!=null)
    if (PrimarysalesrepShr.UserOrGroupId!=null){
    if(!ListPrimarysalesrepShr.isEmpty())
    {
        insert ListPrimarysalesrepShr ;
    }
}
}