Set Required and Optional Address Inputs for Address Field in Drupal 8

This one is dedicated to all my fellow Drupalers. There’s no better exercise for a brain than reading ancient chinese poetry taming Drupal 8. When I’m bored, I turn to Drupal!

Recently I got my Drupal 8 Address module updated and it turned out that from now on street address and postal code inputs are required by default. But my requirement is to have only a “city” input required. How do I do that? Well it’s not that easy as you might think (form alter / widget alter won’t help you there) and there's no UI for that (as of now). After spending some time deep in the sh.. code, I’ve figured out that ALL you need is to just simply create an EventSubscriber and declare your required fields there. Sssssimple!

Okay, enough talking, let me show it to you:

Step 1

Create a file with the following path: your_module/src/EventSubscriber/AddressFormatSubscriber.php

Step 2

Put this code inside a previously created file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
  1. <?php
  2. namespace Drupal\pabc_glue\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Drupal\address\Event\AddressEvents;
  5. class AddressFormatSubscriber implements EventSubscriberInterface {
  6. static function getSubscribedEvents() {
  7. $events[AddressEvents::ADDRESS_FORMAT][] = array('onGetDefinition', 0);
  8. return $events;
  9. }
  10. public function onGetDefinition($event) {
  11. $definition = $event->getDefinition();
  12. // This makes city (locality) field required and leaves
  13. // the rest address fields as optional
  14. $definition['required_fields'] = ['locality'];
  15. $event->setDefinition($definition);
  16. }
  17. }

Note line 18, this is where we declare our required fields.

Step 3

Create, or alter already existing, file your_modiule.services.yml

Step 4

Declare your newly created AddressFormatSubscriber service in your_modiule.services.yml

Step 5

Coffee time ☕️  - clear your caches!