Why Is My Apex Sharing Rule Not Granting Record Access?

Question

I am trying to share Project__c records with the Project Management Team public group when Priority__c is set to “High” using an Apex sharing rule. To achieve this, I created an Apex Sharing Reason called Project_Sharing_Rule and implemented the following trigger and helper class:

Trigger Code

trigger ProjectSharingTrigger on Project__c (after insert, after update) {
    if (Trigger.isInsert || Trigger.isUpdate) {
        ProjectSharingHelper.shareHighPriorityProjects(Trigger.new);
    }
}

Apex Class Code

public class ProjectSharingHelper {
    
    public static void shareHighPriorityProjects(List<Project__c> projects) {
        List<Project__Share> sharesToInsert = new List<Project__Share>();

        Id groupId = [SELECT Id FROM Group WHERE Name = 'Project_management_team' LIMIT 1].Id;

        Projects = [SELECT Id, Priority__c FROM Project__c]; // Unnecessary query?

        for (Project__c proj : projects) {
            if (proj.Priority__c == 'High') {
                Project__Share projectShare = new Project__Share();
                projectShare.ParentId = proj.Id; 
                projectShare.UserOrGroupId = groupId; 
                projectShare.AccessLevel = 'Read'; 
                projectShare.RowCause = Schema.Project__Share.RowCause.Project_Sharing_Rule__c; 

                sharesToInsert.add(projectShare);
            }
        }

        if (!sharesToInsert.isEmpty()) {
            try {
                insert sharesToInsert;
                System.debug('High-priority project shared with team successfully.');
            } catch (DMLException e) {
                System.debug('Error sharing projects: ' + e.getMessage());
            }
        }
    }
}

Answer

The error occurs because the SOQL query for the public group is failing:

Id groupId = [SELECT Id FROM Group WHERE Name = 'Project_management_team' LIMIT 1].Id;

executes a SOQL (Salesforce Object Query Language) query to retrieve the Id of a public group named “Project_management_team” from the Group object. The LIMIT 1 ensures that only one record is returned, even if multiple groups have the same name. The .Id at the end extracts the Id from the returned record and assigns it to the groupId variable.

However, if no group with this name exists, this query will fail with a System.QueryException: List has no rows for assignment to SObject error. To prevent this, it’s best to handle the scenario where no records are found using a try-catch block or by storing the result in a list and checking for null values before accessing the Id.

How to Fix It?

Handle the Missing Group Gracefully

Modify the query to avoid an exception when no records are found. Use the safe navigation operator (?.) to assign null if no group is found.

public class ProjectSharingHelper {

  public static void shareHighPriorityProjects(List<Project__c> projects) {
    List<Project__Share> sharesToInsert = new List<Project__Share>();
    Id groupId = [SELECT Id FROM Group WHERE Name = 'Project_management_team' LIMIT 1]?.Id;

    if (groupId != null) {
      for (Project__c proj : projects) {
        if (proj.Priority__c == 'High') {
          Project__Share projectShare = new Project__Share();
          projectShare.ParentId = proj.Id; 
          projectShare.UserOrGroupId = groupId; 
          projectShare.AccessLevel = 'Read'; 
          projectShare.RowCause = Schema.Project__Share.RowCause.Project_Sharing_Rule__c; 

          sharesToInsert.add(projectShare);
        }
      }
    } else {
      System.debug('Group not found!');
    }

    if (!sharesToInsert.isEmpty()) {
      try {
        insert sharesToInsert;
        System.debug('High-priority project shared with team successfully.');
      } catch (DMLException e) {
        System.debug('Error sharing projects: ' + e.getMessage());
      }
    }
  }
}

The ProjectSharingHelper class is designed to automatically share Project__c records with a public group named “Project_management_team” when their Priority__c field is set to “High”. The method shareHighPriorityProjects takes a list of project records as input and first attempts to retrieve the Id of the public group using a SOQL query. If the group is found, it iterates through the provided projects and checks if their priority is “High”. For each high-priority project, a Project__Share record is created, setting the ParentId to the project’s Id, the UserOrGroupId to the retrieved group Id, the AccessLevel to “Read”, and the RowCause to the Project_Sharing_Rule__c sharing reason. These share records are then collected in a list. If the list is not empty, the method attempts to insert the records into the database inside a try-catch block to handle any potential DMLException errors. If the group is not found, a debug message is logged to indicate the issue, preventing an exception from being thrown due to a missing query result.

Job-Oriented Salesforce Training with 100% Money Back Assurance

Our Salesforce Course is meticulously designed to offer an in-depth understanding of the Salesforce platform, providing you with the crucial skills needed to excel in the CRM domain. The program includes essential modules like Salesforce Admin, Developer, and AI, integrating foundational theory with practical, hands-on experience. By engaging in live projects and real-world assignments, you’ll develop the expertise to solve complex business challenges with confidence, using Salesforce solutions. Our experienced instructors ensure you acquire both technical knowledge and valuable industry insights, enabling you to thrive in the Salesforce ecosystem.

In addition to mastering technical concepts, our Salesforce training in Pune offers personalized mentorship, exam preparation, and interview coaching to boost your career prospects. You’ll have access to comprehensive study materials, practical project experience, and consistent support throughout your learning journey. Upon completion, you’ll be fully prepared for certification exams and equipped with the practical problem-solving skills employers highly value. Embark on your Salesforce career with us—sign up for a Free Demo today!




0
Would love your thoughts, please comment.x
()
x