I am trying to create a string of address in this format: Street, City, State, Country, Zip.
Assume that there is an Address object called addr which has account's shipping address.
Address addr = Account__r.ShippingAddress; // Ignore the syntax here and assume that addr has Address.
My Challenge here is I want to build a string of the addr with comma separated. Example if shipping address has
Shipping Street : 123th Street
Shipping City : SFO
Shipping State/Province : CA
Shipping Zip/Postal Code: 12345
Shipping Country: USA
I want to form a string like String s = 123th Street, SFO, CA, 12345, USA
The catch :
There could be different possiblity that street may not be present or country may not be present in that case the String should logically display the
commas example - city, state, zip -> SFO, CA, 12345
. Also I do not want to display NULL in case street/country/state/zip is not available
. So it is possible that any of the data might be missing and my string should accommodate for missing data and produce the correct comma separated string.
This is what I got started with but I see the logic is getting complex:
String street; String city; String state; String country; String zip;
Address addr = Account__r.ShippingAddress;
street = addr.getStreet() <> NULL ? addr.getStreet() : ''; // to make sure I do not display NULL in string
if(street == NULL){
city = addr.getCity() <> NULL ? addr.getCity() : '';
}else{
city = addr.getCity() <> NULL ? ', ' + addr.getCity() : '';
}
if(city == NULL){
state = addr.getState() <> NULL ? addr.getState() : '';
}else{
state = addr.getState() <> NULL ? ', ' + addr.getState() : '';
}
if(state == NULL){
country = addr.getCountry() <> NULL ? addr.getCountry() : '';
}else{
country = addr.getCountry() <> NULL ? ', ' + addr.getCountry() : '';
}
if(country == NULL){
zip = addr.getPostalCode() <> NULL ? addr.getPostalCode() : '';
}else{
zip = addr.getPostalCode() <> NULL ? ', ' + addr.getPostalCode() : '';
}
String addString = street + '' + city + '' + state + '' + country + '' + zip;