[SalesForce] Auto Populate a Lookup Field based on a field value

We have a custom object "OrderItem__C". This custom object has a lookup field to standard contact object. It also has a field called "Shipping_customer_number__c".

We have this same field(Shipping_customer_number__c) in contact object too. Now when the user enters a shipping customer number in the order item object, based on the value in the shipping customer number field it should auto populate the contact lookup field.

This is because each contact record has an unique shipping customer number. I am trying different ways. Any insights can be helpful for us.

Thank you.

Best Answer

Just create a trigger on OrderItem__c. Since the shipping customer number is unique, when an OrderItem__c record is updated, you can query for the Contact whose Shipping Customer Number matches the new value of the OrderItem__c, and set the Contact lookup on OrderItem__c to match that queried Contact.

You can find information on developing triggers here.

I didn't attempt to compile this and there might be a more elegant way to write it, but it's bulkified and is generally what the logic should be:

trigger SetContactOnOrderItem on OrderItem__c (before update, before insert) {
    Set<Integer> shippingNumbers = new Set<Integer>();

    for (OrderItem__c collectNumFromOrder : Trigger.new) {
        shippingNumbers.add(collectNumFromOrder.Shipping_Customer_Number__c);
    }

    List<Contact> contactList = [SELECT id, Shipping_Customer_Number__c FROM Contact WHERE Shipping_Customer_Number__c IN :shippingNumbers];

    Map<Integer, Contact> shippingNumToContactMap = new Map<Integer, Contact>();

    for (Contact c : contactList) {
        shippingNumToContactMap.put(c.Shipping_Customer_Number__c, c);
    }

    for (OrderItem__c o : Trigger.new) {
        if (o.Shipping_Customer_Number__c != null) {
            o.Contact__c = shippingNumToContactMap.get(o.Shipping_Customer_Number__c).id;
        }
        else {
            o.Contact__c = null;
        }
    }
}