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
CodeFinderCodeFinder 

Copying Fields from one custom object to another

I have some objects created in my DE environment. I want to push them to another object(Different Name) in our company sandbox. how do I achieve it. 

 

I need to send the fields in 'Campaign tempalate' in my DE to 'Template' in Sandbox.

 

Thanks. 

ForcepowerForcepower

I don't know of a straightforward way other than using the meta data api to do the copying. If you are moving certain new fields you defined in your DE to the sandbox, onto the same object, you could just build a package; upload it; install in your sandbox. If the fields need to go on a separate object altogether than what you defined in your DE, I'm afraid you'll need to use the meta data api.

CodeFinderCodeFinder

Do you know how to use the metadata api to achieve this? I know the other way you suggested. I use that to deploy my code or same objects always. I would appreciate if you can share that information. Thanks.

Sean TanSean Tan

Are you using Eclipse with the Force.com IDE to handle the deployment? If so this would definitely be possible with some manipulation of the metadata files / package.xml.

ForcepowerForcepower

Here's a utility class I use. I'd recommend using it only if you have a whole bunch of fields you need to copy - otherwise you may be spending too much time trying to understand it and making it work. It's right now oriented towards grabbing the field defs from a CSV file. So you would still need to create a spreadsheet for your field defs from the DE - may be able to do it just copying from the screen the whle list of fields and dropping it into Excel and saving as CSV.

 

Code listing for MetaData.java

___________________________________________________________________________________

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;

import com.sforce.soap.metadata.*;
import com.sforce.ws.ConnectionException;
/**
* Sample that logs in and creates a custom object through the metadata api
*/
public class MetaData {
private MetadataConnection metadataConnection;
// one second in milliseconds
private static final long ONE_SECOND = 1000;
public MetaData() {
}
public static void main(String[] args) throws Exception {
    MetaData MetaData = new MetaData();
    MetaData.runCreate();
}

public void updateCustomObject(final String name, final String currentName) {
    try {
        CustomObject co = new CustomObject();
        //String name = "MyCustomObject";
        co.setFullName(name + "__c");
        co.setDeploymentStatus(DeploymentStatus.Deployed);
        co.setDescription("Created by the Metadata API");
        co.setEnableActivities(true);
        co.setLabel(name + " Object");
        co.setPluralLabel(co.getLabel() + "s");
        co.setSharingModel(SharingModel.ReadWrite);
        
        
        CustomField nf = new CustomField();
        nf.setReferenceTo(name + "__c");
        nf.setType(FieldType.Text);
        nf.setLabel(co.getFullName() + " Name");
        co.setNameField(nf);
        
        
        CustomField f1 = new CustomField();
        
        f1.setType(FieldType.Number);
        f1.setScale(3);
        f1.setPrecision(4);
        f1.setLabel("Test Num Fld");
        f1.setFullName("MyCustomObject__c.TestNumFld__c");
        co.setFields(new CustomField[] {nf, f1});
        UpdateMetadata updateMetadata = new UpdateMetadata();
        updateMetadata.setMetadata(f1);
        updateMetadata.setCurrentName(name + "__c");
        //AsyncResult[] ars = metadataConnection.update(new UpdateMetadata[]
        //{ updateMetadata });

        
        AsyncResult[] ars = metadataConnection.create(new Metadata[]
                                                                         { f1 });
        AsyncResult asyncResult = ars[0];
        // set initial wait time to one second in milliseconds
        long waitTimeMilliSecs = 1000;
        while (!asyncResult.isDone()) {
            Thread.sleep(waitTimeMilliSecs);
            // double the wait time for the next iteration
            waitTimeMilliSecs *= 2;
            asyncResult = metadataConnection.checkStatus(
            new String[] {asyncResult.getId()})[0];
            System.out.println("Status is: " + asyncResult.getState());
        }
        if (asyncResult.getState() != AsyncRequestState.Completed) {
            System.out.println(asyncResult.getStatusCode() + " msg: " +
            asyncResult.getMessage());
        }
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    } catch (ConnectionException ce) {
    ce.printStackTrace();
    }
}

public CustomField createNumField(final String name, final String apiName, Integer scale, Integer precision, String description) {

        
        
        CustomField field = new CustomField();
        
        field.setType(FieldType.Number);
        field.setScale(scale);
        field.setPrecision(precision);
        field.setLabel(name);
        field.setDescription(description);
        field.setFullName(apiName);
        

        return field;

}
public CustomField createTextField(final String name, final String apiName, Integer length, String description, boolean isEncrypted) {

    
    
    CustomField field = new CustomField();
    
    if (isEncrypted) {
        System.out.println("Creating enc field " + name + " " + apiName + " length:" + length + " " + description);
        field.setMaskChar(EncryptedFieldMaskChar.asterisk);
        field.setMaskType(EncryptedFieldMaskType.lastFour);
        field.setType(FieldType.EncryptedText);            
    }
    else
    if (length > 255) {
        System.out.println("Creating Text Area field " + name + " " + apiName + " length:" + length + " " + description);
        field.setType(FieldType.LongTextArea);
        field.setVisibleLines(5);
    }    
    else {
        field.setType(FieldType.Text);    
        System.out.println("Creating text field " + name + " " + apiName + " length:" + length + " " + description);
        
    }
    field.setLength(length);
    //field.setType(FieldType.Text);        
    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    

    return field;

}
public CustomField createDateField(final String name, final String apiName, String description) {

    
    
    CustomField field = new CustomField();
    
    field.setType(FieldType.Date);
    System.out.println("Creating Date field " +  name + " " + apiName  + " " + description);
        
            
    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    

    return field;

}

public CustomField createFormulaField(final String name, final String apiName, Integer precision, Integer scale, String description, String

formula) {

    
    System.out.println("Creating formula field " + formula + "\n" + name + " " + apiName + " precision:" + precision + " " + description);    
    CustomField field = new CustomField();
    field.setFormula(formula);            
    field.setPrecision(precision);
    field.setScale(scale);
    field.setType(FieldType.Number);        
    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    

    return field;

}

public CustomField createTextFormulaField(final String name, final String apiName, String description, String formula) {

    
    System.out.println("Creating formula field " + formula + "\n" + name + " " + apiName +  " " + description);    
    CustomField field = new CustomField();
    field.setFormula(formula);            
    field.setType(FieldType.Text);        
    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    

    return field;

}

 

____________

More to come

ForcepowerForcepower


public CustomField createLookupField(final String name, final String apiName, String description, String lookup, String relName) {

    
    System.out.println("Creating lookup field " + lookup + "\n" + name + " " + apiName +  " " + description);    
    CustomField field = new CustomField();
    field.setType(FieldType.Lookup);
    field.setReferenceTo(lookup);
    field.setRelationshipName(relName);
    field.setRelationshipLabel(relName);
    //field.setRelationshipOrder(1);

    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    

    return field;

}
public CustomField createPicklistField(final String name, final String apiName, String pickListStr, String delimiter, String description) {

    
    
    CustomField field = new CustomField();
    
    field.setType(FieldType.Picklist);
    field.setLabel(name);
    field.setDescription(description);
    field.setFullName(apiName);
    
    
    StringTokenizer st = new StringTokenizer(pickListStr, delimiter);
    PicklistValue[] pickListValues = new PicklistValue[(st.countTokens())];  
    int i = 0;
    while (st.hasMoreTokens()) {
        pickListValues[i] = new PicklistValue();
        pickListValues[i].setFullName(st.nextToken());
        //pickListValues[i].setDescription(st.nextToken());
        i++;
    }
    Picklist pickList = new Picklist();
    pickList.setPicklistValues(pickListValues);
    field.setPicklist(pickList);
    return field;

}
public void createFields(Vector<CustomField> fieldsVec) {
    int index1 = 0;
    try {
        
        CustomObject co = new CustomObject();
        String objName = fieldsVec.get(0).getFullName().substring(0, fieldsVec.get(0).getFullName().indexOf("."));
        System.out.println("Full name " + objName);
        
        ListMetadataQuery query = new ListMetadataQuery();
        query.setType("CustomObject");
        double asOfVersion = 27.0;
        metadataConnection.listMetadata(new ListMetadataQuery[] {query}, asOfVersion);
        co.setFullName(objName);
        CustomField existingFields[] = co.getFields();
        HashMap<String, String> fieldMap = new HashMap<String, String>();
        for (int j = 0; j < existingFields.length; j++) {
            System.out.println("Full name " + existingFields[j].getFullName());
            fieldMap.put(existingFields[j].getFullName(), existingFields[j].getFullName());
        }
        while (index1 < fieldsVec.size()) {

            int remainingFieldCnt = fieldsVec.size() - index1;
            int fldVecSize = remainingFieldCnt > 10 ? 10 : remainingFieldCnt;
            Metadata[] fields = new Metadata[fldVecSize];
            
            for (int index = 0; index < 10 && index < fieldsVec.size() && index1 < fieldsVec.size(); ) {
                if (!fieldMap.containsKey(fieldsVec.get(index1).getFullName())) {
                    fields[index] = fieldsVec.elementAt(index1);
                    index++;
                }
                index1++;
            }
            AsyncResult[] ars;
            ars = metadataConnection.create(fields);
            AsyncResult asyncResult = ars[0];
            // set initial wait time to one second in milliseconds
            long waitTimeMilliSecs = 1000;
            while (!asyncResult.isDone()) {
                Thread.sleep(waitTimeMilliSecs);
                // double the wait time for the next iteration
                waitTimeMilliSecs *= 2;
                asyncResult = metadataConnection.checkStatus(
                new String[] {asyncResult.getId()})[0];
                System.out.println("Status is: " + asyncResult.getState());
            }
            if (asyncResult.getState() != AsyncRequestState.Completed) {
                System.out.println(asyncResult.getStatusCode() + " msg: " +
                asyncResult.getMessage());
            }
        }
    } catch (InterruptedException ie) {
        System.out.println("IntException: ");
    ie.printStackTrace();
    } catch (ConnectionException ce) {
        System.out.println("ConnException: ");
    ce.printStackTrace();
    }
    System.out.println("index1 is: " + index1 + " " + fieldsVec.size());

}

public void deleteCustomObject(final String uniqueName) {
    try {
        CustomObject co = new CustomObject();
        co.setFullName(uniqueName);
        AsyncResult[] ars = metadataConnection.create(new Metadata[]
        {co});
        //metadataConnection.
        AsyncResult asyncResult = ars[0];
        long waitTimeMilliSecs = 1000;
        while (!asyncResult.isDone()) {
            Thread.sleep(waitTimeMilliSecs);
            // double the wait time for the next iteration
            waitTimeMilliSecs *= 2;
            asyncResult = metadataConnection.checkStatus(
            new String[] {asyncResult.getId()})[0];
            System.out.println("Status is: " + asyncResult.getState());
        }
    } catch (ConnectionException ce) {
    ce.printStackTrace();
    } catch (InterruptedException ie) {
    ie.printStackTrace();
    }

}
/**
* Create a custom object. This method demonstrates usage of the
* create() and checkStatus() calls.
**
@param uniqueName Custom object name should be unique.
*/
private void createCustomObject(final String uniqueName) throws Exception {
    final String label = "My Custom Object";
    CustomObject customObject = new CustomObject();
    customObject.setFullName(uniqueName);
    customObject.setDeploymentStatus(DeploymentStatus.Deployed);
    customObject.setDescription("Created by the Metadata API Sample");
    customObject.setLabel(label);
    customObject.setPluralLabel(label + "s");
    customObject.setSharingModel(SharingModel.ReadWrite);
    // The name field appears in page layouts, related lists, and elsewhere.
    CustomField nf = new CustomField();
    nf.setType(FieldType.Text);
    nf.setDescription("The custom object identifier on page layouts, related lists etc");
    nf.setLabel(label);
    nf.setFullName(uniqueName);
    customObject.setNameField(nf);
    AsyncResult[] asyncResults = metadataConnection.create(
    new CustomObject[]{customObject});
    if (asyncResults == null) {
    System.out.println("The object was not created successfully");
    return;
}
long waitTimeMilliSecs = ONE_SECOND;
// After the create() call completes, we must poll the results of the checkStatus()
// call until it indicates that the create operation has completed.
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());
}


private void runCreate() throws Exception {
    metadataConnection = MetadataLoginUtil.login();
    // Custom objects and fields must have __c suffix in the full name.
    final String uniqueObjectName = "MyCustomObject__c";
    //createCustomObject(uniqueObjectName);
    //updateCustomObject("MyCustomObject", "My Custom Object");
    //createCustomObject("Liver__c");
    //Vector fields = new Vector();
    createFields(readFields("C:\\Users\\ram\\Documents\\XYZ\\Payment2.csv", ","));
    
}


private Vector readFields(String fileName, String delimiter)
{
  Vector<CustomField> fields = new Vector<CustomField>();
 
  try{
  // Open the file that is the first
  // command line parameter
  FileInputStream fstream = new FileInputStream(fileName);
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
      //System.out.println(strLine);
      if (strLine.contains("Field Name")) continue;
      StringTokenizer st = new StringTokenizer(strLine, delimiter);
      if (st.countTokens() >= 4) {
          //System.out.println(strLine);
          String fldName = st.nextToken();
          if (fldName.length() < 4)
              fldName = st.nextToken();
          String fldApiName = st.nextToken();
          String fldType = st.nextToken();
          String description = st.nextToken();
          System.out.println("Field:" + fldName + "," + fldApiName);
          System.out.println("Field Type:" + fldType + ".");
          if (fldType.equals("Formula")) {
              String formula = st.nextToken();          
              int precision = Integer.parseInt(st.nextToken());
              int scale = 1; //Integer.parseInt(st.nextToken());

              CustomField fld = createFormulaField(fldName, fldApiName, precision, scale, description, formula);
              fields.add(fld);
          }          
          if (fldType.equals("FormulaText")) {
              String formula = st.nextToken();          
              formula = formula.replaceAll("#", "\"");
              formula = formula.replaceAll("COMMA", ",");
              CustomField fld = createTextFormulaField(fldName, fldApiName, description, formula);
              fields.add(fld);
          }              
          //if (true) continue;
          if (fldType.equals("Number")) {
              int scale = Integer.parseInt(st.nextToken());
              int precision = Integer.parseInt(st.nextToken());          

              CustomField fld = createNumField(fldName, fldApiName, scale, precision, description);
              fields.add(fld);
          }
          if (fldType.equals("Date")) {
              CustomField fld = createDateField(fldName, fldApiName, description);
              fields.add(fld);
          }          
          if (fldType.equals("Picklist")) {
              String pickListStr = st.nextToken();
              CustomField fld = createPicklistField(fldName, fldApiName, pickListStr, "|", description);
              fields.add(fld);
          }        
          if (fldType.equals("String") || fldType.startsWith("Text")) {
              int length = Integer.parseInt(st.nextToken());
              boolean isEncrypted = fldApiName.contains("_Enc_");
              CustomField fld = createTextField(fldName, fldApiName, length, description, isEncrypted);
              fields.add(fld);
          }    
          if (fldType.equals("Lookup")) {
              String lookup = st.nextToken();
              String relName = st.nextToken();
              CustomField fld = createLookupField(fldName, fldApiName, description, lookup, relName);
              fields.add(fld);
          }              
          
      }
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
        e.printStackTrace();
  System.err.println("Error: " + e.getMessage());
  }
  return fields;  
  }

private HashMap<String, String> readAPIFields(String fileName, String delimiter)
{
    HashMap<String, String> fieldMap = new HashMap<String, String>();
    
    
  try{
      // Open the file that is the first
      // command line parameter
      FileInputStream fstream = new FileInputStream(fileName);
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      String allFieldsStr = "";
      //Read File Line By Line
      while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
          //System.out.println(strLine);
          strLine.replace("\n", delimiter);
          fieldMap.put(strLine.trim().toUpperCase(), strLine);
          allFieldsStr += strLine.trim().toUpperCase() + "," + strLine + ",";
      }
     System.out.println(allFieldsStr);
      //Close the input stream
      in.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
      }
        
      return fieldMap;  
  }

private void convertFields(String fileName, String delimiter, HashMap<String, String> fieldMap)
{
    
    
  try{
      // Open the file that is the first
      // command line parameter
      FileInputStream fstream = new FileInputStream(fileName);
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      String allFieldsStr = "";
      //Read File Line By Line
      while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
          //System.out.println(strLine);
          strLine = strLine.replace("\"", "");
          StringTokenizer st = new StringTokenizer(strLine, delimiter);
          
          while (st.hasMoreTokens()) {
              String nextField = st.nextToken().trim();
              if (fieldMap.containsKey(nextField)) {
                  allFieldsStr += fieldMap.get(nextField) + ",";                  
              }
              else {
                  allFieldsStr += nextField + ",";                  
                  
              }
          }
          //fieldMap.put(strLine.toUpperCase(), strLine);
          allFieldsStr += strLine + ",";
      }
     System.out.println(allFieldsStr);
      //Close the input stream
      in.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
      }
        
      //return fieldMap;  
  }


private void splitLines(String fileName, String delimiter)
{
    
    
  try{
      // Open the file that is the first
      // command line parameter
      FileInputStream fstream = new FileInputStream(fileName);
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      String allFieldsStr = "";
      //Read File Line By Line
      while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
          //System.out.println(strLine);
          strLine = strLine.replace("\"", "");
          StringTokenizer st = new StringTokenizer(strLine, delimiter);
          
          while (st.hasMoreTokens()) {
              String nextField = st.nextToken();
              System.out.println(nextField);
          }

      }
     //System.out.println(allFieldsStr);
      //Close the input stream
      in.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
      }
        
      //return fieldMap;  
  }


}

       

___________________________________________________________________________________

MetaDataLoginUtil.java

 

 

___________________________________________________________________________________

import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.metadata.MetadataConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
/**
* Login utility.
*/
public class MetadataLoginUtil {
public static MetadataConnection login() throws ConnectionException {
final String USERNAME = "abc@xyz.com";
// This is only a sample. Hard coding passwords in source files is a bad practice.
final String PASSWORD = "password<security token>";

final String URL = "https://login.salesforce.com/services/Soap/c/26.0";
final LoginResult loginResult = loginToSalesforce(USERNAME, PASSWORD, URL);
return createMetadataConnection(loginResult);
}
private static MetadataConnection createMetadataConnection(
final LoginResult loginResult) throws ConnectionException {
final ConnectorConfig config = new ConnectorConfig();
config.setServiceEndpoint(loginResult.getMetadataServerUrl());
config.setSessionId(loginResult.getSessionId());
return new MetadataConnection(config);
}
private static LoginResult loginToSalesforce(
final String username,
final String password,
final String loginUrl) throws ConnectionException {
final ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(loginUrl);
config.setServiceEndpoint(loginUrl);
config.setManualLogin(true);
return (new EnterpriseConnection(config)).login(username, password);
}
}

-----------------------------------------------------------------------------------------------------------

Sample input file

-----------------------------------------------------------------------------------------------------------

Transformation #,Field Name,API Name,Field Type,Description,Picklist /Scale/Formula,Precision,Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number,,,,,,
,A_Text_Field_Enc,A_Custom_Object__c.A_Text_Field__c,Text(48),A Text Field,,48,
,A_Picklist,A_Custom_Object__c.A_Picklist__c,Picklist,A Pick List,A|B|C|D,,
,A_Number,A_Custom_Object__c.A_Number__c,Number,A Numbe,1,4, 

 

 

CodeFinderCodeFinder

Wow. I did not think this was this simple. You really use it a lot in your company I guess. 

 

Thanks. WIll let you know if it was helpful after trying it. It will definitely take some time.  

ForcepowerForcepower
Sorry about the long code listing - need to figure out if I can upload files. In any case, good point, Sean. Manipulating the package.xml may provide an easier option than mucking around with code.
ForcepowerForcepower
Yes - it sure does come in handy when you want to just put your field defs into a spreadsheet and just run in it instead of entering each field manually. It does save some time especially if there are a lot of fields and more than one person needs to review the spreadsheet etc before creating the fields.
rah91087rah91087

Thanks sir ......
it really help me lot.

ForcepowerForcepower

Very happy to hear it. Best wishes.

Ram