Reply
Regular Contributor
bdardin
Posts: 13
0
Accepted Solution

retreiving custom object type from what field

I wanted to build a simple trigger on the Event that would make a checkbox true if the What field looked up to one of our custom objects, and false otherwise. But with my attempt at this, it keeps making the checkbox true regardless of what is related to the event and I don't understand why. Here's the code:

 

trigger WorkOrderCheckbox on Event (before insert, before update) {
 for(Event newEvent : trigger.new) {
  if(newEvent.What instanceof SVMXC__Service_Order__c) {
   newEvent.Work_Order__c = true;
  } else {
   newEvent.Work_Order__c = false;
  }
 }
}

What am I doing wrong here?

Regular Contributor
kirkevonphilly
Posts: 32
0

Re: retreiving custom object type from what field

Try this:

 

trigger WorkOrderCheckbox on Event (before insert, before update) {
    for(Event newEvent : trigger.new) {
        Schema.SObjectType objType;
        string target = newEvent.whatID;
        Map<String, Schema.SObjectType> GD = Schema.getGlobalDescribe();
        string keyPrefix;          

        for(Schema.SObjectType describe: GD.values() ){
	        keyPrefix = describe.getDescribe().getKeyPrefix();
	        if(keyPrefix != null && target.startsWith(keyPrefix)){
		        objType = describe;
	            break; //no need to keep looking
            }
        }
        
        if(string.valueof(objType) == 'SVMXC__Service_Order__c') {
            newEvent.Work_Order__c = true;
        }
        else {
            newEvent.Work_Order__c = false;
        }
    }
}

 

Blog: www.CRMScience.com
Twitter: www.twitter.com/kirkevonphilly
LinkedIn: http://www.linkedin.com/in/kirksteffke
Regular Contributor
bdardin
Posts: 13
0

Re: retreiving custom object type from what field

Thank you so much, this worked! Now to study this to figure out why this worked and the other didn't...

Newbie
Mouse Liu
Posts: 2
0

Re: retreiving custom object type from what field

In order to avoid govern limit, it should be like this,

 

trigger WorkOrderCheckbox on Event (before insert, before update) {
    String keyPrefix = Account.SObjectType.getDescribe().getKeyPrefix();
    for (Event newEvent : trigger.new) {
        string target = newEvent.whatID;
        if (target.startsWith(keyPrefix)) {
            newEvent.Work_Order__c = true;
        }
        else {
            newEvent.Work_Order__c = false;
        }
    }
}
Newbie
Mouse Liu
Posts: 2
0

Re: retreiving custom object type from what field

Sorry, Like this,

 

trigger WorkOrderCheckbox on Event (before insert, before update) {
    String keyPrefix = SVMXC__Service_Order__c.SObjectType.getDescribe().getKeyPrefix();
    for (Event newEvent : trigger.new) {
        string target = newEvent.whatID;        
        if (target.startsWith(keyPrefix)) {
            newEvent.Work_Order__c = true;
        }
        else {
            newEvent.Work_Order__c = false;
        }
    }
}