0

I want to delete the apex trigger using code.I used tooling API to create a trigger dynamically through apex code...

Now I want to delete the trigger on click of one button in code itself, but not able to delete..getting following.

DML not allowed on Apex Trigger 
2
  • 1
    Can you add the Apex code that you are using to attempt the delete of the trigger? Dec 13, 2015 at 9:41
  • ApexTrigger a = [select id,name from apextrigger]; delete a; and same error is coming 'DML not allowed on ApexTrigger"
    – Shilpa
    Dec 14, 2015 at 11:12

1 Answer 1

1

To delete a Trigger you have to use the tooling_API , download and copy it in your classes folder

Add this function into the class "ToolingAPI.cls"

public ToolingAPI.SaveResult deleteTrigger(Id sobjectId)
{
    return (ToolingAPI.SaveResult) submitRestCallAndDeserialize(
        '/sobjects/'+'ApexTrigger'+'/'+sobjectId
        ,ToolingAPI.SaveResult.class
        ,'DELETE'
    );
}

And in you code you have to call the function like this:

public static void deleteTrigger(String theName)
{
    ApexTrigger theTriggerToDelete=null;
    //catch the trigger to delete
    try
    {
        theTriggerToDelete = [select id,name from apextrigger where Name=:theName]; 
    }
    catch(System.QueryException e)
    {
        system.debug('bug = ' + e.getMessage());
    }
    if(theTriggerToDelete == null)
        return;
    //catch the id of the trigger to delete
    ID theIdOfTheTriggerToDelete =theTriggerToDelete.Id;
    //using toolingAPI
    ToolingAPI toolingAPI = new ToolingAPI();

    //delete the trigger
    try
    {
        toolingAPI.deleteTrigger(theIdOfTheTriggerToDelete);
    }
    catch(Exception e)
    {
        system.debug('bug = ' + e.getMessage());
    }
} 
4
  • 1
    Have you run this successfully in a production org?
    – Adrian Larson
    Mar 14, 2017 at 17:13
  • Yes its works fine
    – Raphym
    Mar 14, 2017 at 19:35
  • running user needs: Customize Application permission? Author Apex permission?
    – cropredy
    Mar 14, 2017 at 19:47
  • Of course ,only administrator with Author Apex permission can run it .
    – Raphym
    Mar 14, 2017 at 19:50

You must log in to answer this question.

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