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
The NewbieThe Newbie 

Need help with Auto population of field

I have custom object and i want to auto populate a field in the custom object

Custom Object Name: Defective Material
Field Name: Contracter - Data type - lookup(Account)
Field Name: Area Contact - Data type - lookup(contact)

I want to autopopulate Area Contact  automatically when Contracter is selected instead of picking the value. There will be only one Area Contact for the Contracter

Please help me the solution
AnkaiahAnkaiah (Salesforce Developers) 
Hi,

Account have multiple contacts, which contact you need to populate?

if the Account has only one contact then refer the below code.
trigger contactAreaupdate on Defective_Material__c (before insert, before update){

set<id> accids = new set<id>();

for(Defective_Material__c dm:trigger.new){
if(dm.Contracter__c !=Null){
accids.add(dm.Contracter__c);
}
}

map<id,id> mapaccwith = new map<id,id>();

for(contact con:[select id,AccountId from contact where accountId=:accids]){
mapaccwith.put(con.AccountId,con.id);

}

for(Defective_Material__c dm:trigger.new){
if(dm.Contracter__c !=Null){
If(mapaccwith.containskey(dm.Contracter__c)){
dm.Area_Contracter__c = mapaccwith.get(dm.Contracter__c);
}
}
}
}

If this helps, Please mark it as best answer.

Thanks!!