+ Start a Discussion
Suman KunduSuman Kundu 

Dynamically build new Trigger on any object from Apex code

My requirement is something like: I have a generic trigger code, where I need to just change the object name each time and generate a new trigger from an apex code. I think trigger is also saved as a record in salesforce, so I hope it may be possible.

 

Please give me aome idea on it, if it is possible.

sfcksfck

Apex code has no access to the Trigger object. You can't create triggers programmatically. 

 

However you could create an apex class and put as much of the code as you can in there, and call the class from your triggers. That way you only need to cut and paste a tiny bit of code into the triggers, just to call the class. 

 

The class will automatically have access to system.trigger.new, system.trigger.isUpdate and that sort of thing. However you will need to make the class agnostic as to what type of object it is acting on (use the sObject data type, and dynamic SOQL if you need any SOQL). 

 

If you haven't done that before then it might be quite a challenge but once you have done it you will have generalised code that you can re-use on any object.

Chris Berg 6Chris Berg 6
Appearently the Tooling API provides the services you need to create forms, Apex class, triggers etc programitically.  There is probably a standard way to call the Tooling API from an Apex class...even if it's acting as a REST client.  Hoping there are standard objects for this.  I just found this API a few days ago.

http://www.salesforce.com/us/developer/docs/api_tooling/index_Left.htm#StartTopic=Content/sforce_api_objects_apextriggermember.htm