How to extend a field formatter in Drupal 9

I wanted to change how the address field was rendering the address in a View. Since Drupal 9 uses OOPs heavily I thought the best way was to extend the current field formatter in the Address field since we would not have to duplicate the code unnecessarily that way.

Here is what to do.

In your custom module. create a folder src/Plugin/Field/Formatter and in this folder add a new PHP class file and name it like

ExtendedAddressFormatter

In this file use the following scaffolding code.

namespace Drupal\mysite\Plugin\Field\FieldFormatter;

use Drupal\address\Plugin\Field\FieldFormatter\AddressDefaultFormatter;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'extended_address_format' formatter.
 *
 * @FieldFormatter(
 *   id = "extended_address_format",
 *   label = @Translation("Extended Address Format"),
 *   field_types = {
 *     "address",
 *   },
 * )
 */
class ExtendedAddressFormatter extends AddressDefaultFormatter{


  public function viewElements(FieldItemListInterface $items, $langcode) {

    // Get parent elements.
    $elements = parent::viewElements($items, $langcode);



      // Modifying the value. You can manipulate the arrays as you 
     // please. 
      $elements[$delta]['country']['#value'] = 'My new value';
    }

    return $elements;

  }
}

The existing field formatter (parent class) does most of the heavy-lifting which makes our life easier.

Finally, In views config, when you add a field you can select a formatter and this will come up there. On the dropdown select the new Extended Address Format and the field value will be manipulated according to your code.