public static Map<String, List<String>> getFieldDependencies(String objectName, String controllingField, String dependentField) {
Map<String, List<String>> controllingInfo = new Map<String, List<String>>();
Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
List<Schema.PicklistEntry> controllingValues = objType.getDescribe().fields.getMap().get(controllingField).getDescribe().getPicklistValues();
List<Schema.PicklistEntry> dependentValues = objType.getDescribe().fields.getMap().get(dependentField).getDescribe().getPicklistValues();
for(Schema.PicklistEntry currControllingValue : controllingValues) {
controllingInfo.put(currControllingValue.getLabel(), new List<String>());
}
for(Schema.PicklistEntry currDependentValue : dependentValues) {
PicklistValueInfo info = (PicklistValueInfo) JSON.deserialize(JSON.serialize(currDependentValue), PicklistValueInfo.class);
String hexString = EncodingUtil.convertToHex(EncodingUtil.base64Decode(info.ValidFor)).toUpperCase();
Integer baseCount = 0;
for(Integer curr : hexString.getChars()) {
Integer val = 0;
if(curr >= 65) {
val = curr - 65 + 10;
} else {
val = curr - 48;
}
if((val & 8) == 8) {
controllingInfo.get(controllingValues[baseCount + 0].getLabel()).add(currDependentValue.getLabel());
}
if((val & 4) == 4) {
controllingInfo.get(controllingValues[baseCount + 1].getLabel()).add(currDependentValue.getLabel());
}
if((val & 2) == 2) {
controllingInfo.get(controllingValues[baseCount + 2].getLabel()).add(currDependentValue.getLabel());
}
if((val & 1) == 1) {
controllingInfo.get(controllingValues[baseCount + 3].getLabel()).add(currDependentValue.getLabel());
}
baseCount += 4;
}
}
System.debug('ControllingInfo: ' + controllingInfo);
return controllingInfo;
}
调用示例:
String objectName = 'Lead'; // 字段所属的SObject
String controllingField = 'Industry_Picklist__c'; // 控制的字段API
String dependentField = 'Secondary_Industry_Picklist__c'; // 被控制(依赖)的字段API
getFieldDependencies(objectName, controllingField, dependentField);
输出结果:
ControllingInfo: {工业=(汽车, 钢铁), 娱乐=(数码, 电商}
注意:
然而这种方式不能通过“记录类型”去筛选,返回的Map是整个选项列表的依赖关系。如果需要按“记录类型”去筛选,可以通过Meatadata的方式获取依赖关系,这个没有实验,这种方式比较繁琐且速度也比较慢,可以参考这个链接:apex-mdapi 中的getDependentPicklistValuesByRecordType()
参考文档:(1) How To Query Salesforce Picklist Field Values Using SOQL?、(2) Get lists of dependent picklist options in Apex