【问题标题】:How to add a custom field to an existing object in salesforce using Java如何使用 Java 将自定义字段添加到 Salesforce 中的现有对象
【发布时间】:2014-02-19 13:42:59
【问题描述】:

我想将一个外部 id 字段添加到一个还没有它的对象。

我需要什么:

  • 连接到销售团队。
  • 获取可用对象。
  • 获取每个对象的字段。
  • 检查其中一个字段是否是每个对象的外部 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 自定义字段推送到我的组织?

【问题讨论】:

    标签: java salesforce field


    【解决方案1】:

    经过多次尝试和失败,我终于有了我的问题的答案。

    在连接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);
            }
        }
    }
    

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

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

    【讨论】:

      【解决方案2】:
      "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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-01
        • 1970-01-01
        • 2022-11-28
        • 2023-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多