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
Nash12345Nash12345 

Updating Account lookup field upon creating record

Hello my fellow salesforcers,

I'm trying to auto-populate an account lookup field on a custom object (purchase item)  based on the account field on its parent object (purchase order) which, in turn, is a child object to account. 

What I know is workflows don't allow lookup field updates. I also know, or I think I know, that process builder cannot realise this action because the trigger for the auto-population to happen is based on an event prior to the purchase item record being created. 

So am i right to assume that the only way to achieve what I'm looking for if via an apex trigger with the "before create" at the top?

If so, is the following code suitable? I'm currently getting an error on line 11 as it is unable to recognize the relationship of the purchase order's account (supplier) lookup field:

trigger AutoPopulateAccountLookupOnPi on Purchase_Item__c (before insert, before update) {

    //get the Purchase Orders Id's and store it in a set.
    set<Id> POIdSet = new set<Id>();
    for(Purchase_Item__c co: trigger.new){
        if(co.Purchase_Order__c != null){
            opptyIdSet.add(co.Purchase_Order__c );
        }
    }

    //query the purchase order records and get the associated accounts.
    map<id, Purchase_Order__c > POMap = new map<id, Purchase_Order__c >{[SELECT id, Purchase_Order__r.Supplier__c FROM Purchase_Order__c WHERE Id IN: POIdSet]};

    //update the account value based on the purchase order in the record.
    for(Purchase_Item__c co: trigger.new){
        if(POMap.containsKey(co.Purchase_Order__c )){
            co.Account__c = POMap.get(co.Purchase_Order__c ).accountId;

Thanks in advance! 

RaidanRaidan
I think the code after you populate the opptyIdSet should look like this:
//query the purchase order records and get the associated accounts.
    map<id, Purchase_Order__c > POMap = new map<id, Purchase_Order__c >{[SELECT id, Supplier__c FROM Purchase_Order__c WHERE Id IN: POIdSet]};

    //update the account value based on the purchase order in the record.
    for(Purchase_Item__c co: trigger.new){
        if(POMap.containsKey(co.Purchase_Order__c )){
            co.Account__c = POMap.get(co.Purchase_Order__c ).Supplier__c;

 
Nash12345Nash12345
Thanks Raiden - unfortunately its not registering the supplier__c in your code either...
RaidanRaidan
You will have to make sure the field name in the Purchase_Order__c object is correct. Is it called Supplier__c?
Nash12345Nash12345
Supplier__c is actually Account. Yes, that is the actual field name 
RaidanRaidan
So, what do you mean with "Not registering the Supplier__c"? Did you get an error?