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
doughauck-corpdoughauck-corp 

How to set fields on an unknown address in Apex?

I know that the proper way to set the fields on, for example, the Account BillingAddress is to set them individually (e.g. Account.BillingCity = 'Ur').  But I need a way to set the fields of an Address passed as an argument, where I don't know its source.  For example:
Account myAcct = new Account(Name='My Account');
Contact myCont = new Contact(FirstName='My', LastName='Contact');

SetCityAndState(myAcct.BillingAddress, 'Podunk', 'IA');
SetCityAndState(myAcct.ShippingAddress, 'Mahsoxarpachee', 'GA');
SetCityAndState(myCont.MailingAddress, 'Kuppakonakoffee', 'HI');

private void SetCityAndState(Address addr, string city, string state))
{
    addr.City = city;
    addr.State = state;
}

Now, I know the System.Address class has methods to get the values from a random Address field.  But in their wisdom, the SFDC designers have decided not to provide methods to set the values using that class.  (I would call it their "ineffable wisdom", but that would be a lie - I have in fact been "eff"-ing them under my breath all morning.)   There is also a reference in the Developers Guide to a Schema.Address standard object, but the Schema.getGlobalDescribe() method has never heard of it.  It probably isn't what I'm looking for anyway. 

This is for a highly-generalized SObject upload and creation class, so it needs to be generic.  Has anyone found a way to accomplish this (seemingly basic) task?

Thanks,
Doug
Glyn Anderson (Slalom)Glyn Anderson (Slalom)
Something like this might be what you're looking for:

<pre>
Account myAcct = new Account(Name='My Account');
Contact myCont = new Contact(FirstName='My', LastName='Contact');
SetCityAndState(myAcct, 'Billing', 'Podunk', 'IA');
SetCityAndState(myAcct, 'Shipping', 'Mahsoxarpachee', 'GA');
SetCityAndState(myCont, 'Mailing', 'Kuppakonakoffee', 'HI');

private void SetCityAndState(sObject record, String addrType, String city, String state)
{
    record.put( addrType + 'City', city );
    record.put( addrType + 'State', state );
}
</pre>