如何从schema中动态获取RecordTypeName并存入custom object
从Schema动态获取RecordTypeName并存储到自定义对象解决方案
以下方案适用于Salesforce平台场景:
实现步骤
- 第一步:通过Schema类动态拉取目标对象的RecordType元数据
调用Schema.getGlobalDescribe()方法获取全局对象描述结果,再通过目标对象的描述实例调用getRecordTypeInfos()系列方法获取对应RecordType信息,无需硬编码ID或名称,后续RecordType配置变更也不需要调整代码。 - 第二步:按业务规则筛选需要的RecordType
优先通过DeveloperName匹配目标RecordType,不要用Label匹配,避免多语言环境下Label变动导致匹配失效,同时可过滤只保留激活状态的RecordType。 - 第三步:写入自定义对象
提前在自定义对象上创建存储RecordType信息的文本类型字段,将获取到的名称、ID等信息写入对应字段后执行插入/更新操作即可。
可直接运行的Apex代码示例
以下示例为获取Account对象的所有激活RecordType信息,存入自定义对象RecordTypeStorage__c:
// 替换为你的目标对象API名称 String targetObjectApiName = 'Account'; List<RecordTypeStorage__c> storageList = new List<RecordTypeStorage__c>(); // 动态获取对象Schema描述 Schema.DescribeSObjectResult objectDesc = Schema.getGlobalDescribe().get(targetObjectApiName).getDescribe(); // 获取该对象下所有RecordType信息 List<Schema.RecordTypeInfo> rtInfos = objectDesc.getRecordTypeInfos(); for(Schema.RecordTypeInfo rtItem : rtInfos){ // 只处理已激活的RecordType,可按需调整过滤规则 if(rtItem.isActive()){ RecordTypeStorage__c storageItem = new RecordTypeStorage__c(); // 存储RecordType展示名称 storageItem.RecordTypeLabel__c = rtItem.getName(); // 存储RecordType唯一开发者名(推荐优先存储,无多语言兼容问题) storageItem.RecordTypeDeveloperName__c = rtItem.getDeveloperName(); // 可同步存储RecordType ID方便后续关联调用 storageItem.RecordTypeId__c = rtItem.getRecordTypeId(); storageList.add(storageItem); } } // 批量写入自定义对象 if(!storageList.isEmpty()){ insert storageList; }
注意事项
- 若仅需获取单个指定的RecordType,可直接调用
getRecordTypeInfosByDeveloperName()方法定位,无需遍历全量RecordType,性能更高:Schema.RecordTypeInfo targetRt = objectDesc.getRecordTypeInfosByDeveloperName().get('Enterprise_Customer'); - 代码运行前请确认上下文用户拥有自定义对象及对应字段的读写权限,避免权限报错。
内容的提问来源于stack exchange,提问作者Krishna Babu
相关产品推荐
相关产品推荐

