I had to import user data from Prestashop into Craft Commerce v4 and came up with this solution, which uses a Yii module.
// Create address elements from feed-me import
Event::on(
Process::class,
Process::EVENT_STEP_AFTER_ELEMENT_SAVE,
function(FeedProcessEvent $event) {
$addressElement = $this->_createAddress($event->contentData, $event->element->id);
});
I then adapted a function I found in the UpdateController in Commerce 4 that is used to update existing Commerce 3 installations:
private function _createAddress($data, $id): Address
{
$address = new Address();
$address->title = 'Meine Adresse';
// set the owner (user) of the address element
if (isset($id)) {
$address->ownerId = $id;
}
$address->addressLine1 = $data['addressline1'];
if (isset($data['addressline2'])) {
$address->addressLine2 = $data['addressline2'];
}
$address->countryCode = 19;
switch ($data['countryid']) {
case '19':
$address->countryCode = 'CH';
break;
case '1':
$address->countryCode = 'DE';
break;
case '2':
$address->countryCode = 'FR';
break;
case '130':
$address->countryCode = 'LI';
break;
case '10':
$address->countryCode = 'IT';
break;
}
$address->administrativeArea = null;
$address->postalCode = $data['postalcode'];
$address->locality = $data['city'];
$address->dependentLocality = '';
if ($data['firstname'] || $data['lastname']) {
$address->fullName = implode(' ', array_filter([$data['firstname'], $data['lastname']]));
}
if (isset($data['company'])) {
$address->organization = $data['company'];
}
$address->dateCreated = DateTimeHelper::toDateTime($data['dateupdate']);
$address->dateUpdated = DateTimeHelper::toDateTime($data['postalcode']);
Craft::$app->getElements()->saveElement($address, false, false, false);
return $address;
}
You might not need all the code in this function but you will get the idea.