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:
Create a file with the following path:
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
Note line 18, this is where we declare our required fields.
Create, or alter already existing, file
Declare your newly created AddressFormatSubscriber service in
Coffee time ☕️ - clear your caches!