如何在用户Profile为Editor时,从Contact的User__c自动填充Account的Editor__c
解决方案:Contact关联用户同步至Account Editor字段
一、用Record-Triggered Flow实现
步骤1:创建触发流
- 选择对象Contact,触发时机设为记录创建或更新后
- 触发条件配置:
User__c 不为空User__r.Profile.Name 等于 "Editor"
- 勾选「仅在记录满足条件时运行流」
步骤2:添加更新Account的元素
- 新增「更新记录」元素,对象选Account
- 更新规则选「指定条件以更新记录」,条件设为
Account.Id 等于 {!$Record.AccountId} - 设置字段赋值:
Editor__c = {!$Record.User__r.Name}(如果要存用户ID,就改成{!$Record.User__c}) - 批量场景无需额外配置,Flow默认支持批量处理
二、用Apex Trigger实现
完整触发代码
trigger ContactSyncEditorToAccount on Contact (after insert, after update) { // 筛选出User__c有值且更新过的Contact List<Contact> targetContacts = new List<Contact>(); for(Contact con : Trigger.new) { if(con.User__c == null) continue; // 新增直接处理,更新时只处理User__c变更的记录 if(Trigger.isInsert || con.User__c != Trigger.oldMap.get(con.Id).User__c) { targetContacts.add(con); } } if(targetContacts.isEmpty()) return; // 查询符合Profile要求的用户 Set<Id> userIds = new Set<Id>(); for(Contact con : targetContacts) { userIds.add(con.User__c); } Map<Id, User> editorUsers = new Map<Id, User>([ SELECT Id, Name FROM User WHERE Id IN :userIds AND Profile.Name = 'Editor' ]); // 批量组装要更新的Account Map<Id, Account> accountsToUpdate = new Map<Id, Account>(); for(Contact con : targetContacts) { User editor = editorUsers.get(con.User__c); if(editor != null && con.AccountId != null) { accountsToUpdate.put(con.AccountId, new Account( Id = con.AccountId, Editor__c = editor.Name // 存ID就改成editor.Id )); } } if(!accountsToUpdate.isEmpty()) { update accountsToUpdate.values(); } }
关键注意点
- 确保当前运行上下文有User对象Profile字段、Contact的AccountId和User__c字段的读取权限
- 代码做了批量处理,避免循环内SOQL/DML,符合Salesforce governor限制
- 可根据需求调整
Editor__c的赋值内容(用户名/用户ID)
内容的提问来源于stack exchange,提问作者Shreyas
相关产品推荐
相关产品推荐

