Tuesday 15 March 2016

Delete Components before and after Component Updates in a deployment in Salesforce

Guys, As we all know that Ant is such a great migration tool. I have described how we can set-up ANT on our local machine and migrate desired component to Salesforce org.

Today I am going to describe how we can delete component from salesforce org using ANT. Salesforce has provided a way of achieving it through some well defined desctructiveChanges.xml .

Later on, it would took two at least migration attempts for clearing-up dependencies between components and deleting those respectively.
For example if one custom field is being used by an apex class then we can not delete that field until we remove that field's active presence from apex class. For this purpose, Salesforce unveiled two new type of xmls

1. destructiveChangesPre.xml
2. destructiveChangesPost.xml

Lets understand with an example. Let say there are two fields amount__c,department__c on Account Object and there is one class ShowingResult that use one field amount__c.
Public class ShowingResult {

   Public void ShowingResult()
   {
       Account acc = new Account{Name = 'testAcc', amount__c = 1232};
       insert acc;    
   }

}

In order to delete these two fields we need to make some required changes in apex class first. then system would allow us to delete amount__c field. Generally it would take two steps but the way is described below would do our job in one attempt.

Here is your modified Apex Class:
Public class ShowingResult {

   Public void ShowingResult()
   {
       Account acc = new Account{Name = 'testAcc'}; // with modification
       insert acc;    
   }

}

Now we just need to create three xml files(as below) and run these.System would run desctructiveChangesPre.xml then package.xml for updating component where we have removed dependencies. finally it would run desctructiveChangesPost.xml.
Your desctructiveChangesPre.xml

    
        Account.department__c
        CustomField
    
    36.0

Your Package.xml:

    
        ShowingResult
        ApexClass
    
    36.0

Your desctructiveChangesPost.xml:

    
        Account.amount__c
        CustomField
    
    36.0

Keep these xml in src folder and run migration.