Jan 18, 2017 · Updated: Nov 09, 2017 · by Tim Kamanin
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:
Create a file with the following path: your_module/src/EventSubscriber/AddressFormatSubscriber.php
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.
Create, or alter already existing, file your_modiule.services.yml
Declare your newly created AddressFormatSubscriber service in your_modiule.services.yml
Coffee time ☕️ - clear your caches!
Hey, if you've found this useful, please share the post to help other folks find it: