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
mits430mits430 

Compareing object type using "Event.What.type" is not work

I'd like to compare Object type using "Event.What.type" in Trigger method.
Then I wrote some code. but, it didn't work rightly.

 

It rather seems "Event.What" was null.
How should I do that it work correctly. or please tell me other way.

 

Here is the code.

trigger TestTrigger on Event (after insert) {

for (Event rec : Trigger.new) {
// "rec.What" is null...
if (rec.What.type == "ownCustonObject__c") {
}
}
// ... some code

}

 

Would someone please reply this.

 

 

Mitsutaka.

Best Answer chosen by Admin (Salesforce Developers) 
HarmpieHarmpie

Not 100% sure if my suggestion here is the best approach to do this, but it will probably work:

 

1) Use a Schema.getGlobalDescribe to obtain all objects

2) Iterate over the objects and per object add the property 'keyPrefix' to a map (keyPrefix->objectname)

3) Then in you trigger, compare the first 3 positions of What.Id to the keys inside this map

4) Result is your object

All Answers

HarmpieHarmpie

Not 100% sure if my suggestion here is the best approach to do this, but it will probably work:

 

1) Use a Schema.getGlobalDescribe to obtain all objects

2) Iterate over the objects and per object add the property 'keyPrefix' to a map (keyPrefix->objectname)

3) Then in you trigger, compare the first 3 positions of What.Id to the keys inside this map

4) Result is your object

This was selected as the best answer
mits430mits430

Hi Harmpie.

 

I did it!

Thank you very much that is exactly what I needed!  and result is so fine.

 

(Somehow, I thought that it might have to get a database definition.

but, I didn't know how to get it globally...)

 

 

and following is my code.

trigger TestTrigger on Event (after insert) {

Map<String, String> s2o = new Map<String, String>();
Map<String, Schema.SObjectType> schemas = Schema.getGlobalDescribe();
Set<String> keys = schemas.keySet();

// creating map that able to look up object name by key prefix.
for (String key : keys) {
Schema.SObjectType schema = schemas.get(key);
Schema.DescribeSObjectResult d = schema.getDescribe();
s2o.put(d.getKeyPrefix(), d.getName());
}

for (Event rec : Trigger.new) {
if (rec.WhatId == null)
continue;

String prefix = ((String)(rec.WhatId)).substring(0,3);
String objName = s2o.get(prefix);

if (objName.equals('fooObject__c')) {
// some process...
}
}
}

 

 

Mitsutaka.