function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shawn Reichner 29Shawn Reichner 29 

Contacts from parent to child account via Apex trigger - getting Illegal Assignment error

Hello, 

I am attempting some apex outside of the normal areas for me as I am new and stil learning. 

I am trying to when a child account is created for an existing account, clone the Contacts and then list them under the child account as well.  I know this isnt best practice, however it is what I am tasked with and the following is the code I currently have, although I am getting an error on line 29 and the error is - Illegal Assignment From Set to Id   Can anyone help me to get thsi working so that I can show in Sandbox and help to show the duplication and why this would be a bad idea?

Thanks,
 
trigger CopyAccountContactsToChild on Account (before insert) {

    Set<Account> AcctsToUpdate = new Set<Account>();
    List<Id> ParentAccounts = new List<Id>();
    List<Contact> ConsToSwap = new List<Contact>();
    
    
    For(Account A : Trigger.New){
        
        If(A.Parent_Account_Custom__c != null){
           
            AcctsToUpdate.add(A);   
        }   
    }
    
    For(Account A2 : AcctsToUpdate){
        ParentAccounts.add(A2.Parent_Account_Custom__c);
    }
    
    For(Id pAtoLookAt : ParentAccounts){
        List<Contact> consToGet = new List<Contact>([SELECT ID, AccountId FROM Contact WHERE AccountId =: pAtoLookAt]);
        
        For(Contact c3 : consToGet){
        ConsToSwap.add(c3);
        }
    }
    
    For(Contact AFinal : ConsToSwap){
        AFinal.AccountId = AcctsToUpdate;
    }   

}

 
Prady01Prady01
Hello there, here is the same code, From What I understood.
 
trigger CopyAccountContactsToChild on Account (before insert) {

   map<Id, id> parentToChildMap = new map<Id, Id>();
   List<Contact> conInsrtLst = new List<Contact>();
    
    for(Account acc : Trigger.New){
        If(acc.Parent_Account_Custom__c != null){
            parentToChildMap.put(acc.parentId, acc.id);
        }   
    }
	
	List<Contact> conLst = new list<Contact>([select id , name, AccountId from Contact where AccountId in: parentToChildMap.keys()]);
	for(Contact con: conLst){
			contact cont = new Contact();
				cont.Name = con.Name;
				cont.AccountId = parentToChildMap.get(con.AccountId);
				conInsrtLst.add(cont);
	}
	
	if(conInsrtLst.size()>0){
		insert conInsrtLst;
	}
    
   

}

Hope this helps!

Thank you
Prady01​
Prady01Prady01
Woop's one issue, below is the code.
 
trigger CopyAccountContactsToChild on Account (after insert) {

   map<Id, id> parentToChildMap = new map<Id, Id>();
   List<Contact> conInsrtLst = new List<Contact>();
    
    for(Account acc : Trigger.New){
        If(acc.Parent_Account_Custom__c != null){
            parentToChildMap.put(acc.parentId, acc.id);
        }   
    }
	
	List<Contact> conLst = new list<Contact>([select id , name, AccountId from Contact where AccountId in: parentToChildMap.keys()]);
	for(Contact con: conLst){
			contact cont = new Contact();
				cont.Name = con.Name;
				cont.AccountId = parentToChildMap.get(con.AccountId);
				conInsrtLst.add(cont);
	}
	
	if(conInsrtLst.size()>0){
		insert conInsrtLst;
	}
    
   

}

Thank you
PSM​
Malni Chandrasekaran 2Malni Chandrasekaran 2
Shawn,
Is your code incomplete? I am just asking to understand completely. because, I could not see any DML to clone (insert) the contacts.
Please consider my suggestion - If the business requirement is to list the contacts of parent accounts as well under the child account, you can always pull the data and present it in business view (pagelayout or VF page)

The query to pull the contact of Parent Account
​Select Contact.Id, Contact.Name, Contact.AccountId, Account.parentid from Contact where  accountid in (Select parentid from account where id = <var which holds childs account id>)

Prady01 has given the required code and I dont want to replicate the same here, however, 
Few comments in your code to help in future:
trigger CopyAccountContactsToChild on Account (before insert) {

    Set<Account> AcctsToUpdate = new Set<Account>();
    List<Id> ParentAccounts = new List<Id>();
    List<Contact> ConsToSwap = new List<Contact>();
    
    
    For(Account A : Trigger.New){
        
        If(A.Parent_Account_Custom__c != null){
           
            AcctsToUpdate.add(A);   
        }   
    }
    
    For(Account A2 : AcctsToUpdate){
        ParentAccounts.add(A2.Parent_Account_Custom__c);
    }
    
    For(Id pAtoLookAt : ParentAccounts){ // You may avoid the for loops (in bold) and can put the codes in first for loop within the if condition.
        List<Contact> consToGet = new List<Contact>([SELECT ID, AccountId FROM Contact WHERE AccountId =: pAtoLookAt]);
        
        For(Contact c3 : consToGet){
        ConsToSwap.add(c3);
        }
    }
    
    For(Contact AFinal : ConsToSwap){
        AFinal.AccountId = AcctsToUpdate;  // You are trying to assign set  (collection of) data where primitive (single id) is expected.
    }   

}

 
Shawn Reichner 29Shawn Reichner 29
All, thanks for your help!  I have decided to go with a Visualforce page embedded into the Child Account page layout and I have that working, but I am stumped on writing a test class for it.  Can anyone help with that?  Her eis my VF page and Extension code.. Thanks in advance...


VF Page - 
 
<apex:page standardcontroller="Account" extensions="myController2" tabStyle="Account">
<apex:pageBlock >
<apex:pageblocksection title="Contacts" columns="1">
<apex:pageblocktable value="{!accounts}" var="cons1">
<apex:column headervalue="Name">
<apex:outputLink value="/{!cons1.id}">{!cons1.Name}</apex:outputLink>
</apex:column>
<apex:column value="{!cons1.Phone}"/>
<apex:column value="{!cons1.Email}"/>
</apex:pageblocktable>
</apex:pageblocksection>
</apex:pageBlock>
</apex:page>

Extension Class -
 
public class myController2{

    public mycontroller2(ApexPages.StandardController controller) {

    }

    public list<contact> cons;
    public List<Contact> getAccounts() {
    Id recid=apexpages.currentpage().getparameters().get('id');  
    Account lesson=[select id,ParentId from Account where Id=:recid limit 1];
 
        cons=[select id,Phone,Email,Name from contact where Accountid=:lesson.ParentId];
        if(cons.size()>0){return cons;}    
        else{
        return null;
        }
     
      
    }

}