元の質問 : How can I get the contact owners the same as the account owners?
サンプルコードがありそうで見つかりません。
仕方ない書いてみるか。
trigger AccountTrigger on Account (after update) {
Set<Id> AccountIdSet = new Set<Id>();
Map<Id,Id> AccountMap = new Map<Id,Id>();
if (Trigger.isUpdate) {
for (Account acc : Trigger.old){
AccountMap.put(acc.Id,acc.OwnerId);
}
}
if (Trigger.isUpdate) {
for (Account acc : Trigger.new){
AccountIdSet.add(acc.Id);
}
}
List<Account> AccountList = [SELECT Id ,OwnerId, (SELECT Id,OwnerId from Contacts) FROM Account WHERE Id =:AccountIdSet];
List<Contact> updateContactList = new List<Contact>();
for (Account acc : AccountList){
Id OwnerId = (Id)AccountMap.get(acc.Id);
if (OwnerId != null && OwnerId != acc.OwnerId){
if (acc.Contacts.size() >0){
for (Contact con : acc.Contacts){
Contact co = new Contact();
co.Id = con.Id;
co.OwnerId = acc.OwnerId;
updateContactList.add(co);
}
}
}
if ( updateContactList.size() >0) update updateContactList;
}
}
テストクラスも書いてみました。
@isTest
public class AccountTrigger_test {
@isTest
public static void test01() {
Profile p;
User u;
p = [select Id from Profile where Name = 'Standard Platform User'];
u = new User();
u.FirstName = 'test';
u.LastName = 'user';
u.Alias = 'testuser';
u.Email = 'test_user@test20220802.com';
u.UserName = u.Email;
u.EmailEncodingKey = 'ISO-2022-JP';
u.TimeZoneSidKey = 'Asia/Tokyo';
u.LocaleSidKey = 'ja_JP';
u.LanguageLocaleKey = 'ja';
u.profileId = p.Id;
insert u;
Test.startTest();
Account acc = new Account();
acc.name = 'test';
insert acc;
Contact con = new Contact();
con.LastName ='test1';
con.AccountId = acc.Id;
insert con;
acc.OwnerId = u.Id;
update acc;
List<Contact> ContactList = [SELECT Id ,OwnerId FROM Contact WHERE AccountId =: acc.Id];
System.assertEquals(ContactList[0].OwnerId, u.Id);
Test.stopTest();
}
}
public without sharing class TRG_Account {
public static void beforeTrigger(List<Account> newList, List<Account> oldList, Boolean isInsert, Boolean isUpdate) {
}
public static void afterTrigger(List<Account> newList, List<Account> oldList, Boolean isInsert, Boolean isUpdate, Boolean isDelete) {
Set<Id> AccountIdSet = new Set<Id>();
Map<Id,String> AccountMap = new Map<Id,string>();
if (isUpdate) {
for (Account acc : oldList){
AccountMap.put(acc.Id,acc.Phone);
}
}
if (isUpdate) {
for (Account acc : newList){
AccountIdSet.add(acc.Id);
}
}
List<Account> AccountList = [SELECT Id ,Phone, (SELECT Id,Phone from Contacts) FROM Account WHERE Id =:AccountIdSet];
List<Contact> updateContactList = new List<Contact>();
for (Account acc : AccountList){
String sPhone = (String)AccountMap.get(acc.Id);
if (sPhone != null && sPhone != acc.Phone){
if (acc.Contacts.size() >0){
for (Contact con : acc.Contacts){
Contact co = new Contact();
co.Id = con.Id;
co.Phone = acc.Phone;
updateContactList.add(co);
}
}
}
if ( updateContactList.size() >0) update updateContactList;
}
}
}