5

This might seem to be a fairly simple question, but I am unable to figure out how to use the fields returned by a Polymorphic SOQL query.

For example: I ran the following query in dev console's query editor:

SELECT TYPEOF WHAT
WHEN OPPORTUNITY THEN Name,StageName
WHEN ACCOUNT THEN Name
ELSE Email
END
FROM EVENT

It shows that I have one record which matches this criteria, but it doesn't show the record details. Here is the output: enter image description here

When I run this segment of code in Anonymous window, the list only prints WhatId and the Id of the event itself.

list<Event> newlist=[SELECT TYPEOF WHAT
WHEN OPPORTUNITY THEN StageName
ELSE Email
END
FROM EVENT];

system.debug(newlist);

if(newlist.get(0).What instanceof Opportunity){
    //what should I do here to access fields of opportunity?
}

I understand that I can fetch the WhatId from the list and use that to query the fields on Opportunity object. But if I need to run the DML again to get the required fields, what is the use of the polymorphic DML statement?

Any help is appreciated. Many thanks.

1 Answer 1

5

Here is an example of how to retrieve field values returned from Polymorphic query.

list<Event> newlist=[SELECT TYPEOF WHAT
                    WHEN OPPORTUNITY THEN StageName
                    ELSE Email
                    END
                    FROM EVENT];

To access the StageName value of the Opportunity, first create an instance of Opportunity object based on evt.What as below and then you will get the StageName.

for(Event evt:newlist){
    if(evt.What instanceof Opportunity){
        //what should I do here to access fields of opportunity?
        System.debug('evt.WhatId=' + evt.WhatId);
        Opportunity opty = evt.What;
        System.debug('opty=' + opty);
        System.debug('opty.StageName=' + opty.StageName);
    }
}

Debug log

But if you try to access StageName like this way evt.What.StageName without typecasting to Opportunity then compiler will complain as StageName is not an attribute of that Polymorphic object.

1
  • 1
    Thank you so much! This works :) Jan 9, 2020 at 8:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .