I have not yet had to do this in Craft 5, but the following is how I did it in Craft 4 - it required some custom module code to hook into the EVENT_AFTER_SAVE_ELEMENT
event which triggers when a User is registered. You might also be able to use EVENT_AFTER_ASSIGN_USER_TO_DEFAULT_GROUP
instead.
use Craft;
use yii\base\Event;
use craft\services\Elements;
use craft\events\ElementEvent;
use craft\elements\Address;
...
// --------------------------------------------
// SAVE ADDRESS AFTER REGISTRATION
// --------------------------------------------
Event::on(
Elements::class,
Elements::EVENT_AFTER_SAVE_ELEMENT,
function(ElementEvent $e) {
// bail out on console requests
if (Craft::$app->request->isConsoleRequest) { return; }
// Bail out on CP requests
if (Craft::$app->request->isCpRequest) { return; }
// bail out if it's not a user element being saved, just to triple check ourselves
if (!$e->element instanceof \craft\elements\User) { return; }
// else continue...
$add1 = Craft::$app->request->getBodyParam('address');
$userId = $e->element->id;
$address = new Address();
$address->ownerId = $userId;
$address->title = 'Address';
$address->fullName = '';
$address->addressLine1 = $add1['addressLine1'];
$address->addressLine2 = $add1['addressLine2'];
$address->locality = $add1['locality'];
$address->postalCode = $add1['postalCode'];
$address->countryCode = 'GB';
$address->administrativeArea = $add1['administrativeArea'];
// Save the address
Craft::$app->getElements()->saveElement($address);
}
);
The registration form is as normal, with {{ actionInput('users/save-user') }}
and then you can name the address inputs however you like e.g. name="address[addressLine1]"
and then wire them up in the function above. This code actually originally came from a Craft 3 site where it was even more difficult if I recall (as Addresses were part of Commerce but not really part of core Craft), so it's possible there might even be a more native way now - I just went for the simplest possible upgrade route from 3 to 4. Hopefully it can at least help you get it working in 5.