diff --git a/src/elements/Address.php b/src/elements/Address.php index 5bde3825611..3e33c913b97 100644 --- a/src/elements/Address.php +++ b/src/elements/Address.php @@ -4,6 +4,7 @@ use CommerceGuys\Addressing\AddressFormat\AddressField; use CommerceGuys\Addressing\AddressInterface; +use CommerceGuys\Addressing\Subdivision\SubdivisionUpdater; use Craft; use craft\base\Element; use craft\base\NameTrait; @@ -583,6 +584,32 @@ protected function cacheTags(): array return $tags; } + /** + * @inheritdoc + */ + public function beforeSave(bool $isNew): bool + { + // commerceguys/addressing 2.0.x - remap changed subdivision IDs + // update the subdivision ID to its ISO code where available + if (isset($this->countryCode)) { + if (isset($this->administrativeArea)) { + $this->administrativeArea = SubdivisionUpdater::updateValue( + $this->countryCode, + $this->administrativeArea, + ); + } + // Andorra is the only country with remapped localities. + if ($this->countryCode == 'AD' && isset($this->locality)) { + $this->locality = SubdivisionUpdater::updateValue( + $this->countryCode, + $this->locality, + ); + } + } + + return parent::beforeSave($isNew); + } + /** * @inheritdoc * @throws InvalidConfigException diff --git a/src/helpers/Cp.php b/src/helpers/Cp.php index 69825f26562..2f27c665b43 100644 --- a/src/helpers/Cp.php +++ b/src/helpers/Cp.php @@ -2082,7 +2082,10 @@ public static function addressFieldsHtml(Address $address): string $belongsToCurrentUser ? 'address-level2' : 'off', isset($visibleFields['locality']), isset($requiredFields['locality']), - [$address->countryCode, $address->administrativeArea], + array_values(array_filter([ + $address->countryCode, + array_key_exists('administrativeArea', $visibleFields) ? $address->administrativeArea : false, + ], fn($v) => $v !== false)), true, ) . self::_subdivisionField( @@ -2091,7 +2094,11 @@ public static function addressFieldsHtml(Address $address): string $belongsToCurrentUser ? 'address-level3' : 'off', isset($visibleFields['dependentLocality']), isset($requiredFields['dependentLocality']), - [$address->countryCode, $address->administrativeArea, $address->locality], + array_values(array_filter([ + $address->countryCode, + array_key_exists('administrativeArea', $visibleFields) ? $address->administrativeArea : false, + array_key_exists('locality', $visibleFields) ? $address->locality : false, + ], fn($v) => $v !== false)), false, ) . static::textFieldHtml([