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

18 Jan · by Tim Kamanin · 2 min read

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:

<?php
namespace Drupal\pabc_glue\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\address\Event\AddressEvents;

class AddressFormatSubscriber implements EventSubscriberInterface {

  static function getSubscribedEvents() {
    $events[AddressEvents::ADDRESS_FORMAT][] = array('onGetDefinition', 0);
    return $events;
  }

  public function onGetDefinition($event) {
    $definition = $event->getDefinition();
    // This makes city (locality) field required and leaves
    // the rest address fields as optional
    $definition['required_fields'] = ['locality'];
    $event->setDefinition($definition);
  }

}

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!

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments