Wednesday 6 January 2016

How to access Compound field values in Apex Salesforce

Happy New Year 2016...!

What is Compound Field?

Compound fields group together multiple elements of primitive data types, such as numbers or strings, to represent complex data types, such as a location or an address.

What are the fields available in Address field?

Address compound fields are available in the SOAP and REST APIs in API version 30.0 and later. The list of available fields are,

Accuracy
City
Country
CountryCode
Latitude
Longitude
PostalCode
State
StateCode
Street

How to access value in Apex?

By using Compound address, you don't need to represent each address field names in query like BillingCity, BillingState, etc. Just refer the Compound field, here i am referring BillingAddress.

  1. for(Account acc : [SELECT Name, BillingAddress FROM Account])
  2. {
  3.     Address addr = (Address) acc.BillingAddress;
  4.     if(addr!=null)
  5.     {
  6.         System.debug('Address Value: '+addr);
  7.     }
  8. }

You can get debug value as below,

System.Address[getCity=null;getCountry=India;getCountryCode=IN;getGeocodeAccuracy=null;getPostalCode=null;getState=null;getStateCode=null;getStreet=null;]

How to access specific field values?

From the Address class you can get specific field values as like below,

  1. for(Account acc : [SELECT Name, BillingAddress FROM Account])
  2. {
  3.     Address addr = (Address) acc.BillingAddress;
  4.     if(addr != null)
  5.     {
  6.         System.debug('# City '+addr.getCity());
  7.         System.debug('# Country '+addr.getCountry());
  8.     }
  9. }

Reference:

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/compound_fields_address.htm

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...