How can I use the keyword “whatid”?

203    Asked by DavidWHITE in Salesforce , Asked on Jun 3, 2024

 I am currently working at a particular company and my task is to develop a management application. A client wants to implement a feature where they can Identify the task based on specific criteria, such as priority level and completion status. How can I use the whatid keyword in my code so that I can do this particular task? 

Answered by Crowny Hasegawa

 In the context of Salesforce, the “whatid” keyword can be used to deal with the task and event object. In Salesforce, the “whatid” field is a polymorphic foreign key that can reference various objects such as accounts, contacts, opportunities, and custom objects.

Here is how you can use the “whatId” field in Salesforce apex code to identify the tasks based on specify criteria:-

Public class TaskProcessor {
    // Method to retrieve and process tasks based on criteria
    Public static void processTasks(Id recordId) {
        // Query tasks related to the specified record with specific criteria
        List tasksToProcess = [SELECT Id, Subject, Priority, Status
                                     FROM Task
                                     WHERE WhatId = :recordId
                                     AND Priority = ‘High’
                                     AND Status = ‘Not Started’];
        // Process the retrieved tasks
        For(Task t : tasksToProcess) {
            // Perform operations on tasks that meet the criteria
            System.debug(‘Processing Task: ‘ + t.Subject);
            // Example: Update task status to ‘In Progress’
            t.Status = ‘In Progress’;
        }
        // Update the processed tasks
        If(!tasksToProcess.isEmpty()) {
            Update tasksToProcess;
            System.debug(‘Updated task statuses to In Progress.’);
        } else {
            System.debug(‘No tasks found matching the criteria.’);
        }
    }
}

In this particular example:-

We have a task processor class with a process task method that can accept the I’d parameters which would represent the record.

Inside this particular method, we perform SOQL queries to retrieve the tasks that are related to the specific record with a priority of high and a status of not started.

We iterate in this example through the retrieved task and then perform operations.

We update their status to “in progress” and log a message if the tasks meeting criteria are found “tasksToProcess.is empty”.

Thus this code would demonstrate a structured approach to how you can Process tasks based on specific criteria by using the “WhatId” field in Salesforce Apex.



Your Answer

Interviews

Parent Categories