1

I am new to Salesforce and I want to understand a small thing.

My question is: Why MailingPostalCode field is not found in Address object?

When I search Contact object from workbench and right click on returned object ID and open in new window, I get to see MailingPostalCode field.

I investigated and found that MailingPostalCode field is getting fetched from Address object. However, when I go to Address object I do not find it..!!

Please explain..

2

When trying:

Contact c = [Select Id, MailingAddress From Contact Limit 1];
system.debug(c);
system.debug(c.MailingAddress.postalcode);

We get the error:

Invalid foreign key relationship: Contact.MailingAddress

However this works as expected:

Contact c = [Select Id, MailingAddress From Contact Limit 1];
system.debug(c);
system.debug( ( (Address)c.MailingAddress ).postalcode);

OR

Address a = (Address)c.MailingAddress;
system.debug(a.postalcode);
system.debug(a.getPostalCode());
  • That's interesting, the need to cast. I've always assumed it just works, but I haven't specifically tried it. – sfdcfox Oct 17 '16 at 23:19
1

You are probably misinterpreting the output. The Address object contains the various fields without the "Mailing" (or any other) prefix. The fields just happen to appear to be grouped together because the fields are sorted in alphabetical order.

Besides MailingAddress, you can also access the individual fields on contact: MailingGeocodeAccuracy, MailingCity, MailingCountry, MailingCountryCode, MailingLatitude, MailingLongitude, MailingPostalCode, MailingState, MailingStateCode, MailingStreet.

So, you could address the postal code through the MailingAddress object:

record.MailingAddress.PostalCode

Or through the "classic" field directly:

record.MailingPostalCode
  • @Robi - Did you try this answer because as I explained below it throws an error. If you got it to work (you accepted it) I would be interested to know. – Eric Oct 17 '16 at 22:30
  • While testing, found another way of fetching : Contact c = [Select Id, mailingAddress, mailingPostalCode From Contact where mailingPostalCode != null Limit 1]; system.debug(c); system.debug(c.mailingPostalCode); – Kamruzzaman Oct 18 '16 at 13:59
  • @Robi Yes, that's exactly what I mentioned in my answer. MailingAddress.PostalCode and MailingPostalCode contain the same value. While that code (disappointingly) doesn't work in Apex Code without a cast (as mentioned by Eric), other platforms, such as the Apex Data Loader, should be able to understand the address.postalcode notation just fine. – sfdcfox Oct 18 '16 at 14:18

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.