我想将一个外部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.");
}
假定“字段”是每个对象的字段数组,而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自定义字段推送到我的组织?
经过多次尝试和失败之后,我终于对我的问题有了答案。
在连接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);
}
}
}
这样,我们为组织中的对象创建了一个自定义字段(如果该对象尚不存在)。
可以修改它,并以各种方式使用它来创建多个自定义字段,具体取决于用例。希望能对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句