Skip to content

magento 2.4 save region as string in address

I’m importing my customers via code and part of that import involves addresses and regions. If the region is in the database, I have no issue in importing it, I simply get the region id by the region interface:

/** @var MagentoDirectoryModelRegionFactory $region */
$region = $this->regionFactory->create()->loadByName($regionName, $countryId);
$regionId = $region->getRegionId();

This works. However, most of my customers have no regionId in the database.

On backend/frontend, when there is no region entry in the database, customers can fill in a text input and the region name is saved in the address. I’d like to accomplish the same thing with my code, that is: I’d like to save the region name even if there is no database entry.

How can I achieve that?