0

I want to add an External id field to an object that does not already have it.

What I need:

  • Connect to the salesforce.
  • Get objects available.
  • Get the fields of each object.
  • Check if one of the fields is the external id for each object.

What I need it to do:

  • If the external id field does not exist: create it for this object.
  • Another method that deletes it at the end of my processes (migration processes).

Following code is used to connect to salesforce org:

ConnectorConfig PartnerCfg = new ConnectorConfig();
PartnerCfg.setUsername(USERNAME);
PartnerCfg.setPassword(PASSWORD);
try {
    myConnection = com.sforce.soap.partner.Connector.newConnection(PartnerCfg);
} catch (ConnectionException e) {
    System.out.println("An error occured while connecting to the org.");
}

Assume that "Fields" is an array of fields for each object and EXT_ID__C is a constant that contains "Ext_Id__c" string.

Here is the code I've made so far:

customFieldExists = false;
for (int j = 0; j < fields.length; j++) {
    Field field = fields[j];
    if ("customField__c".equals(field.getName())) {
        customFieldExists = true;
    }
    // If field is the last of the object
    if (j == fields.length - 1) {
        if (customFieldExists == false) {
            CustomField customField = new CustomField();
            customField.setFullName(EXT_ID__C);
            customField.setLabel("Ext_Id");
            customField.setType(FieldType.Text);
            customField.setExternalId(true);
            customField.setLength(18);
            // Here Should come the code to upload the field and its properties
            // To salesforce org current object.
            System.out.println("Created customField__c field in object " + ObjectName);
        }
    }
}

How do I push the extId custom field to my organization?

2 Answers 2

2

After multiple tries and fails, I finally have an answer to my question.

In the connection try/catch, update the following code:

try {
        myConnection = com.sforce.soap.partner.Connector.newConnection(PartnerCfg);
        metadataCfg.setSessionId(trgtConnection.getSessionHeader().getSessionId());
        metadataConnection = com.sforce.soap.metadata.Connector.newConnection(metadataCfg);
    } catch (ConnectionException e) {
            System.out.println("An error occured while connecting to the org.");
    }

Then, the following code iterates through each object to check if the field we're looking for exists, and if not, it creates it. Assume that sObjects variable is an array of sObjects.

DescribeSObjectResult[] objects = myConnection.describeSObjects(sObjects);
for (int i = 0; i < objects.length; i++) {
    // object #i is stored in desObj variable.
    DescribeSObjectResult desObj = objects[i];
    // Get the name of the sObject
    String objectName = desObj.getName();
    boolean customFieldExists = false;
    // Iterate through the fields to get properties of each field
    for (int j = 0; j < fields.length; j++) {
        Field field = fields[j];
        if ("customField__c".equals(field.getName())) {
            extIdExists = true;
        }
        // If field is the last of the object
        if (j == fields.length - 1) {
            // Create a new custom field
            CustomField customField = new CustomField();
            // Add its properties to the custom field
            customField.setFullName(objectName + "." + customField__c);
            customField.setLabel("customField");
            customField.setType(FieldType.Text);
            customField.setExternalId(true);
            customField.setLength(18);
            // Push it to the object
            metadataConnection.create(new Metadata[] {customField});
            System.out.println("Created customField__c field in object " + objectName);
        }
    }
}

This way, we create a custom field for an object in the org if it doesn't already exist.

It can be modified and used in various ways to create multiple custom fields depending on the use case. Hope it can help.

Sign up to request clarification or add additional context in comments.

Comments

0
"import java.util.ArrayList;

import com.sforce.async.Error;
import com.sforce.soap.metadata.*;
import com.sforce.soap.metadata.FieldType;
import com.sforce.soap.metadata.SaveResult;
import com.sforce.soap.partner.*;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.wsdl.SfdcApiType;
/**
 * Login utility.
 */
public class PartnerLoginUtil {
        public static PartnerConnection login() throws ConnectionException {
                final String USERNAME = ""[email protected]"";
                // This is only a sample. Hard coding passwords in source files is a bad practice.
                final String PASSWORD = ""Password+securityToken"";
                final String URL = ""https://login.salesforce.com/services/Soap/u/31.0"";

                //Quick Start Step 3: Walk through the Java Sample Code
                final LoginResult loginResult = loginToSalesforce(USERNAME, PASSWORD, URL);
                //System.out.println(loginResult);
                return createPartnerConnection(loginResult);
        }
        public static void main(String[] args) throws Exception {
                // TODO Auto-generated method stub
                try {
                        PartnerConnection e = PartnerLoginUtil.login();
                        PartnerLoginUtil p= new PartnerLoginUtil( );
                        p.readCustomObjectSync();

                } catch (ConnectionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
        private static PartnerConnection createPartnerConnection(
                        final LoginResult loginResult) throws ConnectionException {
                final ConnectorConfig config = new ConnectorConfig();
                config.setServiceEndpoint(loginResult.getServerUrl());
                config.setSessionId(loginResult.getSessionId());
                return new PartnerConnection(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 PartnerConnection(config)).login(username, password);
        }
        public void readCustomObjectSync() throws Exception {
                try {
                        DescribeGlobalSObjectResult[] sObjects = null;
                        DescribeGlobalResult objectsDesc;
                        PartnerConnection enterpriseconnection=PartnerLoginUtil.login();;
                        objectsDesc = enterpriseconnection.describeGlobal();
                        sObjects=objectsDesc.getSobjects();

                        for(DescribeGlobalSObjectResult dgs:sObjects)
                        {  
                                Boolean extId=false;
                                DescribeSObjectResult sfobj= enterpriseconnection.describeSObject(dgs.getName());
                                Field[] f= sfobj.getFields();
                                System.out.println(""verifying external field for ""+dgs.getName()+""label is""+dgs.getLabel());
                                for(Field f1:f)
                                {
                                        if(f1.isExternalId())
                                        {
                                                extId=true;        
                                                System.out.println(""external Id available for ""+dgs.getName()+""label is""+dgs.getLabel());
                                                break;
                                        }

                                }
                                if(extId==false)
                                {
                                        System.out.println(""creating extrnal field for ""+dgs.getName());
                                        createCustomExtField(dgs.getName());
                                }
                        }
                }
                catch (ConnectionException ce) {
                        ce.printStackTrace();
                }
        }


        private void createCustomExtField(String name) {
                // TODO Auto-generated method stub
                CustomField cs = new CustomField();
                cs.setFullName(name+"".CustExtField__c"");
                cs.setLabel(""CustExtField"");
                cs.setType(FieldType.Number);
                cs.setExternalId(true);
                cs.setPrecision(10);
                cs.setScale(8);
                try {
                        MetadataConnection metadataConnection = MetadataLoginUtil.login();
                        SaveResult[] results = metadataConnection
                                        .createMetadata(new CustomField[] {cs});

                        for (SaveResult r : results) {
                                if (r.isSuccess()) {
                                        System.out.println(""Created component: "" + r.getFullName());
                                } else {
                                        System.out
                                        .println(""Errors were encountered while creating ""
                                                        + r.getFullName());
                                        for (com.sforce.soap.metadata.Error e : r.getErrors()) {
                                                System.out.println(""Error message: "" + e.getMessage());
                                                System.out.println(""Status code: "" + e.getStatusCode());
                                        }
                                }
                        }
                } catch (ConnectionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

        }

}

Regards,

Naveen

SSE , Salesforce CI expert group

http://www.autorabit.com"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.