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
AK9999AK9999 

SOQL Query on Event to get Opportunity (custom fields)

I need help to query on Task Event to get Opportunity custom fields like Campaign name and Product name. I would like to filter my tasks related to Oppty and Lead based on product name and campaign name.

String LeadObjName= 'Lead'; String OpportunityObjName= 'Opportunity'; String Completedsatatus= 'Completed';
String queryStr='select Id, Subject, Status,ActivityDate,Priority, OwnerId, Owner.Name, Owner.IsActive,Description,WhoId,Who.Name,WhatId, What.Name,AccountId,Account.Name '; queryStr+=' from Task where OwnerId = :userId and (Who.Type =:LeadObjName OR What.Type = :OpportunityObjName ) '; queryStr+=' and Status !=:Completedsatatus'; queryStr+=' order by ActivityDate ASC, Priority DESC';
Ques: We want to access opportunity and lead custom fields in my query but not able to add custom fields here in this query Thanks in Advance!
{!pramod_nishane}{!pramod_nishane}
Hi AK9999,

Since the "WhatId" can refer to any number of object types, you can't reference a custom field from a single one of those objects.
And you can't use subquery for Task object.
If you are using Apex, then you can break it into two separate queries and get the required data.

Task t = [select WhatId fromTask where Id = 'x'];
Your_Object__c m = [select customField__c from Your_Object__c where Id =: t.WhatId];

Let me know in case of any concerns.

Please mark this answer as the solution/ best answer if it solves your purpose so that it can help other community members.

Thanks,
Pramod Nishane
Salesforce Consultant
Varasi LLC
www.varasi.com