Working on a mailing that includes contacts full address details. And I'm encountering an issue for UK addresses where the county is abbreviated in the same way US states are. I've never seen such 3-char abbreviations used in the UK and it will cause confusion. Omitting the county is not an option either. Sadly the standard address hooks for mailings are limited.
Googling yielded the following page which has code I'm trying to use in a custom Civicrm extension. So far my attempts are failing miserably. I'm not very familiar with PHP, so please excuse and gently correct whatever atrocities I might be committing in the code below.
https://forum.civicrm.org/index.php%3Ftopic=20687.0.html
The extension is meant to provide two new tokens to mailings:
- {contact.province}: prints the State / Province full name (as in {contact.state_province_name}). Not the same name in case this brings any conflict with the existing one
- {contact.complete_address}: prints the full contact's address with the same format set in the label address customization
The article is quite old and uses APIv2, so I've resorted to adapt it to APIv4. In doing so my PHP errors have disappeared but I'm not seeing any results in "Preview as HTML" yet when editing a test mailing.
My hooks code below:
// Works, the new hooks show up in the list when editing mailings //
function mailhooks_civicrm_tokens( &$tokens ) {
$tokens['contact'] = array(
'contact.province' => 'Province',
'contact.complete_address' => 'Complete Address',
);
}
// Not returning anything, the tags are not interpreted at all //
function mailhooks_civicrm_tokenValues( &$values, &$contactIDs ) {
require_once 'CRM/Utils/Address.php';
foreach($contactIDs as $id){
$address = \Civi\Api4\Address::get()
->addSelect('street_address', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'city', 'postal_code', 'state_province_id:label', 'country_id:label')
->addWhere('contact_id', '=', $id)
->execute();
$values[$id]['contact.complete_address'] = nl2br(CRM_Utils_Address::format($address[$id]));
$values[$id]['contact.province'] = $address[$id]["state_province_id:label"];
}
}
The output from the API Explorer (dummy address):
(1) [
{
"id": 3,
"street_address": "3 Kings Road",
"supplemental_address_1": null,
"supplemental_address_2": null,
"supplemental_address_3": null,
"city": "Hitchin",
"postal_code": "SG5 0AZ",
"state_province_id:label": "Hertfordshire",
"country_id:label": "United Kingdom"
}
]
Partial HTML preview:
SG5 0AZ, {contact.province}
United Kingdom
{contact.complete_address}
Email template:
{contact.postal_code}, {contact.province}
{contact.country}
{contact.complete_address}
{contact.province}
when{contact.state_province_name}
already exists with the full UK County name?