1

I have a custom object Vendor__c and on that object I have a lookup field to Accounts. I want to populate that Accounts lookup field with the account related to another lookup field Projects__c which comes from a custom object projects. I am very new to Apex but this is what I have so far:

trigger Vendor__c {
Set<Id> accountIds = new Set<Id>();
    for(proj from trigger.new){
        accountIds.add(proj.Customer__c);
    
}
    List<Account> accountsWithProj = [SELECT Id, (SELECT Customer__c FROM Projects__r) FROM Account WHERE Id IN :accountIds];
    for(account from List<Account> accountsWithProj = [SELECT Id, (SELECT Customer__c FROM Projects__r) FROM Account WHERE Id IN :accountIds];){
        vendor.Account__c = null;
        if(!vendor.Project__c.isEmpty()){
            vendor.Account__c = vendor.Project__r.Customer__c;
        }
    }
    update accountsWithProj;
}

Can someone assist me with trying to get this field to auto-populate with this information? I am open to new suggestions as well. Thank you!

1
  • Welcome Alex. I'd primarily look into how to implement separation of concerns in Apex to make this code a little cleaner - trailhead.salesforce.com/en/content/learn/modules/…. Also, can you clean up the code snippet? There are syntax issues, like your for-loop containing a semi-colon inside the parens, and some of the variables don't make sense. It'll be easier for me to help you if these things are syntactically/logically correct. Jun 16, 2021 at 18:36

1 Answer 1

1

I think you want something like this.

Set<Id> projectIds = new Set<Id>();
for(Vendor__c vendor : Trigger.new){
  projectIds.add(vendor.Project__c);
}
Map<Id,Project__c> projectsById = new Map<Id,Project__c>(SELECT Id, Customer__c FROM Project__c WHERE Id IN :projectIds);
for(Vendor__c vendor : Trigger.new){
  Id accountId = projectsById.get(vendor.Project__c)?.Customer__c;
  vendor.Account__c = ( accountId == null || vendor.Account__c !== null) ? vendor.Account__c : accountId;
}

This gets the project ids, queries the projects (and their accounts) into a map.

Then in the second loop, the project id is used to get the queried project. If its account is not null, then it's used to fill the account for this vendor.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .