如何从特定对象的字段标签中找到 API 字段名称?

How to find the API name of field from an label of field from a particular sobject?

如何从特定对象的字段标签中找到 API 字段名称。

很难在 salesforce 中找到字段 api 名称,这确实是一个微不足道的问题,许多开发人员在处理项目时发现这个问题很棘手。

作为代码片段放在这里,方便搜索。

这是根据对象的标签找出字段的 api 名称的代码片段。

public static String getMyAPIName(String objectName, String fieldLabel ) {
    
    SObjectType type = Schema.getGlobalDescribe().get(objectName);
    Map<String,Schema.SObjectField> mfields = type.getDescribe().fields.getMap();
    
    for(String strField : mfields.keySet())
    {
        SObjectField fl = mfields.get(strField);
        if(fieldLabel == fl.getDescribe().getlabel())
        {
            return strField;
        }
    }
    
    return '';
}
SELECT EntityDefinition.QualifiedApiName, QualifiedApiName, Label
FROM FieldDefinition 
WHERE EntityDefinition.QualifiedApiName = 'Account' AND Label = 'Parent Account'

输出“ParentId”就好了,没有描述和循环