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
Aparna Hegde 8Aparna Hegde 8 

I want the ability to filter report on SObject with Activity and filter for latest activity.

I want the ability to filter report on SObject with Activity and filter for latest activity. There is an idea posted 11 yrs ago for this functionality and unfortuantely its not available. I know creating a custom field on activity helps, looking at coding to achieve this. Any help on documentation around this?
 
Arun Kumar 1141Arun Kumar 1141

Hi Aparna,

Using Apex code, you may use the Salesforce Reports and Analytics API to filter a report on an SObject with activity and extract only the most recent activity. Here's an example of how you can achieve this:

// Query the report using the Reports and Analytics API
Reports.ReportResults reportResults = Reports.ReportManager.runReport(reportId, true);

// Get the report data
Reports.ReportFactWithDetails reportData = (Reports.ReportFactWithDetails) reportResults.getFactMap().get('T!T');

// Iterate through the report rows
for (Reports.GroupingValue reportRow : reportData.getRows()) {
    // Get the field values for the SObject and activity fields
    String sobjectId = (String) reportRow.getRows().get(0).getDataCells().get(0).getLabel();
    String activityName = (String) reportRow.getRows().get(0).getDataCells().get(1).getLabel();
    Date activityDate = (Date) reportRow.getRows().get(0).getDataCells().get(2).getLabel();

    // Process the latest activity
    // You can perform any necessary logic or store the data as needed
    System.debug('SObject ID: ' + sobjectId);
    System.debug('Activity Name: ' + activityName);
    System.debug('Activity Date: ' + activityDate);
}


The report ID you want to run should be substituted for reportId in the example above. The code uses Reports to access the report results. The Reports.ReportFactWithDetails object obtains the report data after executing it via the ReportManager.runReport method. It retrieves the field values for the SObject and activity fields by iterating through the report's rows.
 

Please note that you will need to have the appropriate permissions and access to run reports and use the Reports and Analytics API in your Salesforce org.

 

Please refer to this documentation on reports given by Salesforce for more information -- Report (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_analytics_report_data.htm)

 

If this helps, mark it as the best answer.
 

Thanks

Arun