如何使用Java将自定义字段添加到salesforce中的现有对象

时间:2014-02-19 13:43:00

标签: java salesforce field

我想将一个External id字段添加到一个尚未拥有它的对象中。

我需要什么:

  • 连接到salesforce。
  • 获取对象。
  • 获取每个对象的字段。
  • 检查其中一个字段是否为每个对象的外部ID。

我需要做什么:

  • 如果外部id字段不存在:为该对象创建它。
  • 在我的流程结束时(迁移流程)删除它的另一种方法。

以下代码用于连接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.");
}

假设“Fields”是每个对象的字段数组,EXT_ID__C是包含“Ext_Id__c”字符串的常量。

这是我到目前为止所做的代码:

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);
        }
    }
}

如何将extId自定义字段推送到我的组织?

2 个答案:

答案 0 :(得分:2)

经过多次尝试并失败后,我终于回答了我的问题。

在连接try / catch中,更新以下代码:

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.");
    }

然后,以下代码遍历每个对象以检查我们正在寻找的字段是否存在,如果不存在,则创建它。假设sObjects变量是一个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);
        }
    }
}

这样,我们就为组织中的对象创建一个自定义字段(如果它尚不存在)。

可以根据用例以各种方式修改和使用它来创建多个自定义字段。希望它可以提供帮助。

答案 1 :(得分: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 = ""username@gmail.com"";
                // 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"