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
Dhaval PanchalDhaval Panchal 

How to remove custom fields using Metadata API (Bulk delete custom fields)..

Hello,

 

I want to delete 500+ custom fields. Is there any solution to mass remove custom fields? I have tried with metadata Api using below code. But it gives me below error.

 

Object with id:04s900000037qo4AAA is InProgress
Error status code: INVALID_CROSS_REFERENCE_KEY
Error message: In field: members - no CustomField named Custom_Field__c found
Object with id:04s900000037qo4AAA is Error

 

Below is the code:

 


    public void deleteCustomField(String fullname) throws Exception
    {
        CustomField customField = new CustomField();
        customField.setFullName(fullname);
        
        UpdateMetadata updateMetadata = new UpdateMetadata();
        updateMetadata.setMetadata(customField);
        updateMetadata.setCurrentName(fullname);
        
        AsyncResult[] asyncResults  = metadataConnection.delete(new Metadata[] {customField});
 
        long waitTimeMilliSecs = ONE_SECOND;
 
        do
        {
            printAsyncResultStatus(asyncResults);
            waitTimeMilliSecs *= 2;
            Thread.sleep(waitTimeMilliSecs);
            asyncResults = metadataConnection.checkStatus(new String[]{asyncResults[0].getId()});
        } while (!asyncResults[0].isDone());
 
        printAsyncResultStatus(asyncResults);
    }

 


    private void printAsyncResultStatus(AsyncResult[] asyncResults) throws Exception {
        if (asyncResults == null || asyncResults.length == 0 || asyncResults[0] == null) {
            throw new Exception("The object status cannot be retrieved");
        }

        AsyncResult asyncResult = asyncResults[0]; //we are creating only 1 metadata object

        if (asyncResult.getStatusCode() != null) {
            System.out.println("Error status code: " +
                    asyncResult.getStatusCode());
            System.out.println("Error message: " + asyncResult.getMessage());
        }

        System.out.println("Object with id:" + asyncResult.getId() + " is " +
            asyncResult.getState());
    }

 

Is there any other solution (any app) to removing custom fields?

 

Thanks in advance,

 

Dhaval Panchal

Best Answer chosen by Admin (Salesforce Developers) 
Dhaval PanchalDhaval Panchal

Finally i got solution using below descructiveChanges.xml file

 

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>codepkg</fullName>
    <types>
        <members>MyCustomObject__c.Custom_Field_del__c</members>
        <name>CustomField</name>
    </types>
    <types>
        <members>MyCustomObject__c.Custom_Field2__c</members>
        <name>CustomField</name>
    </types>
    <version>17.0</version>
</Package>

All Answers

hitesh90hitesh90

Hi,

 

You can use Force.com IDE to delete custom fields using Metadata API.

see This Link :- Metadata & the Metadata API

 

 

Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator
My Blog:- http://mrjavascript.blogspot.in/

Dhaval PanchalDhaval Panchal
Thanks Hitesh,

I am using Force.com in eclipse. Do you have any steps to do this process?
hitesh90hitesh90

Hi,

 

Below is the steps as per your requirements

 

1. Log in Eclipse in your own project in which you want to delete the fields.

2. Double click and Open the Metadata for the Object whose fields you want to delete.

3. When the metadata is shown up. find the tag  and select all those which u want to delete.

4. Click on Backspace to delete and deploy to server so as it is reflected in Production or Sandbox from where you copied.

 

Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator
My Blog:- http://mrjavascript.blogspot.in/

Dhaval PanchalDhaval Panchal
Hi,

I did same thing, I have removed tag <fields></fields> but problem is that once i remove this tag, and try to save (locally) it refresh it from server again. So I am not able to remove any fields. I have tried so many times but it is not reflecting on server (I am using developer edition).
hitesh90hitesh90

remove the tag, and try to save to server. Not refresh from server.

Dhaval PanchalDhaval Panchal

See below screenshot.

 

https://docs.google.com/file/d/0B6cPMtpRoi9FTnZqMmdHaDZpU3c/edit?usp=sharing

 

I am following below steps.

 

1. Open xml file

2. Select field tag to remove

3. Save (local)

4. Then save to server.

5. Also tried deploy to server.

 

I thing i have to check my ide settings.

Bhawani SharmaBhawani Sharma
Use descructiveChanges.xml. Easy to setup and use.
hisalesforcehisalesforce

I was on the same situation ....One thing is sure ,from eclipse you cannot do.

 

Go to other path rather than eclipse.

May be From Ant we can do it.......and there are other ide, but i am not confirm about it.

Dhaval PanchalDhaval Panchal
Hello,

I tried with descructiveChanges.xml, and it successfully deletes objects but not able to remove custom fields. Even I am getting below success message in console.

undeployCode:
[sf:deploy] Request for a deploy submitted successfully.
[sf:deploy] Request Id for the current deploy task: 09S90000000EhvZEAS
[sf:deploy] Waiting for server to finish processing the request...
[sf:deploy] Request Status: Completed
[sf:deploy] Finished request 09S90000000EhvZEAS successfully.

BUILD SUCCESSFUL
Total time: 15 seconds

But when I check in salesforce.com it is not deleted.

below is my descructiveChanges.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>codepkg</fullName>
<types>
<members>Custom_Field1__c</members>
<members>Custom_Field2__c</members>
<name>CustomField</name>
</types>
<version>17.0</version>
</Package>

Dhaval PanchalDhaval Panchal

Finally i got solution using below descructiveChanges.xml file

 

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>codepkg</fullName>
    <types>
        <members>MyCustomObject__c.Custom_Field_del__c</members>
        <name>CustomField</name>
    </types>
    <types>
        <members>MyCustomObject__c.Custom_Field2__c</members>
        <name>CustomField</name>
    </types>
    <version>17.0</version>
</Package>

This was selected as the best answer
Team WorksTeam Works

Is it possible to add all the 500 custom fields into this XML automatically OR you need to generate this XML manually?

pooja@magichorse.compooja@magichorse.com

You can create csv files with object and field list then use below java codes to generate xml file.

 

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import au.com.bytecode.opencsv.CSVReader;

public class GenerateDestructiveXML {	
	public static void main(String[] args) throws IOException {
		GenerateDestructiveXML obj=new GenerateDestructiveXML();
		obj.generateXML();
	}
	public void generateXML() throws IOException{
        Object lstColumnName[]={"Object Name","Field Name","Count"};
        List<ObjectList> lstObjectList = new ArrayList<ObjectList>();
        lstObjectList = readDataFromCSV("E:\\CustomObject_Fields_ComponentCount.csv", lstColumnName);//Use your path here
        
        if(lstObjectList.size()>0)
        {
        	String strXML = "";
        	strXML = "<?xml version='1.0' encoding='UTF-8'?>";
        	strXML += "\n<Package xmlns='http://soap.sforce.com/2006/04/metadata'>";
        	strXML += "\n\t<fullName>codepkg</fullName>";
        	for(ObjectList obj:lstObjectList)
        	{
        		if(obj.count != null && obj.count<=0)
        		{
        			strXML += "\n\t<types>";
        			strXML += "\n\t\t<members>" + obj.name.trim() + "." + obj.field.trim() + "</members>";
        			strXML += "\n\t\t<name>CustomField</name>";
        			strXML += "\n\t</types>";
        		}
        	}
        	strXML += "\n\t<version>17.0</version>";
        	strXML += "\n\t</Package>";
        	FileUtils.writeStringToFile(new File("E:\\DestructiveChanges.xml"), strXML);//Use your path here
        }
		
	}
	public class ObjectList{
		public String name;
		public String field;
		public Integer count;
	}
    public List<ObjectList> readDataFromCSV(String FileName,Object[] lstColumnName)
	{
		String parentId=null;
		ArrayList dt=new ArrayList();
		CSVReader reader =null;
		List<ObjectList> lstObjectList = new ArrayList<ObjectList>();
		try
		{
			reader = new CSVReader(new FileReader(FileName));
			String[] nextLine;
			int index = 0;
			int parentIndex = -1;
			boolean firstline = false;
			while ((nextLine = reader.readNext()) != null)
			{
				Object[] row = new Object[lstColumnName.length];
				if(firstline == false)
				{
					for (int i = 0; i < nextLine.length; i++)
					{
						System.out.println("nextLineindex[i]::::" + nextLine[i]);
					}
					firstline = true;
				}
				else
				{
					//System.out.println("index::::" + index);
					ObjectList obj = new ObjectList();
					boolean addRow = false;
					for (int i = 0; i < lstColumnName.length; i++)
					{
						
						if(lstColumnName[i].toString().trim().equalsIgnoreCase("Object Name")){
							obj.name = nextLine[i].trim();
							if(obj.name != null) addRow = true;
							System.out.println("@@@ Object Name: " + obj.name);
						}
						if(lstColumnName[i].toString().trim().equalsIgnoreCase("Field Name")){
							obj.field = nextLine[i].trim();
							System.out.println("@@@ field Name: " + obj.field);
						}
						if(lstColumnName[i].toString().trim().equalsIgnoreCase("Count")){
							obj.count = Integer.valueOf(nextLine[i].trim());
							System.out.println("@@@ count: " + obj.count);
						}
						System.out.println(lstColumnName[i] + "::::" + nextLine[i]);
						row[i] = nextLine[i];
					}
					if(addRow) lstObjectList.add(obj);
					dt.add(row);

				}//end of else

			}//end of while
		}
		catch (Exception e)
		{
			System.out.println("Exception: in read csv"+e);
		}
		finally
		{
			try{
				reader.close();
				reader=null;
			}catch(Exception e){
				System.out.println("Exception "+e);
			}
		}

	return lstObjectList;
	}
}

 

Team WorksTeam Works

Hi Pooja,

 

I hope this is the standard java code i can always use for Object/field files? The reason to ask i do not know java :)

 

Thanks!

pooja@magichorse.compooja@magichorse.com
I am using this code to generate XML file. You can convert this code in your language. Its a simple read and write operation. Just see formats of files which you can get from salesforce.com account -> migration tool. I have created destructiveChanges.xml file based on below format
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>codepkg</fullName>
<types>
<members>MyCustomObject__c.Custom_Field_del__c</members>
<name>CustomField</name>
</types>
<types>
<members>MyCustomObject__c.Custom_Field2__c</members>
<name>CustomField</name>
</types>
<version>17.0</version>
</Package>