1

I have a lookup field to a child object on the Account object i want to update with a record Id for a child object.

I want to compare the text value in either the Billing State/Province field (or if blank, the Billing Country field) on the Account record to the Name_c field on the Locale_c object, returning the record Id for the matching Locale record to update the lookup field on the Account object.

1
  • Jason - welcome to SFSE. I think you'll find you'll get more assistance here if you reword your question to be more explicit about the various SObjects and their schema relationship to each other. Is Locale__c a child of Account? And what object does the lookup field on Account refer to? Is the use case a user interface question (VF) or a trigger question or something else -- when does the event/transaction occur?
    – cropredy
    Mar 4, 2014 at 2:30

1 Answer 1

1

You can do this via a trigger. Something like:

trigger Account_bi on Account (before insert)
{
    // map of accounts keyed by the locale search text
    Map<String, List<Account>> accsBySearchField=new Map<String, List<Account>>();

    // build the map - iterate the accounts and extract the state or country field
    for (Account acc : trigger.new)
    {
        String searchStr=acc.BillingState!=null?acc.BillingState:acc.BillingCountry;

        if (null!=searchStr)
        {
            // add the account to the list of those with the same search string - these will all be updated with the same locale lookup
            List<Account> accs=accsBySearchStr.get(searchStr);
            if (null==accs)
            {
                accs=new List<Account>();
                accsBySearchStr.put(searchStr, accs);
            }

            accs.add(acc);
        }
    }

    // pull back all locale objects where the name matches a search string
    List<Locale__c> locales=[select id, Name__c from Locale__c where Name__c IN :accsBySearchStr.keySet()];
    for (Locale__c locale : locales)
    {
        // get the account records matching the name of the locale and set the lookup
        List<Account> accs=accsBySearchStr.get(locale);
        if (null!=accs)
        {
            for (Account acc : accs)
            {
                acc.Locale__c=locale.id;
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.