1

I am working on a craftcms + commerce project and I need to add a shipping address to new user during its registration process. The idea is to have a shipping address added to any newly registered user (no billing address needed).

Is it possible to add shipping address fields in the same registration process or do i need to create 2 step form or something?

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.