How to Migrate phone numbers into phone_number fields.

Created on 1 August 2024, 5 months ago

I'm documenting this mostly as an aid to developers in the future that need to migrate string-based phone number values into fields that are configured to use this module's phone_number field type. I had a hard time finding the expectations for migrating to this field type.

This field expects data to be formatted using the E.164 "International public telecommunication numbering plan" standard so you'll need to add a processing step to your migration. Here's a simple example of formatting a string like "543-209-2234" to the E.164 standard (assumes US region).

<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

/**
 * Adds the area code to phone numbers without an area code.
 *
 * @MigrateProcessPlugin(
 *  id = "format_phone_E164",
 * )
 */
class FormatPhoneE164 extends ProcessPluginBase {

  /**
   * {@inheritDoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    if (empty($value)) {
      return NULL;
    }
    $phoneNumberUtil = PhoneNumberUtil::getInstance();
    $phoneNumber = $phoneNumberUtil->parse($value, 'US');
    $value = $phoneNumberUtil->format($phoneNumber, PhoneNumberFormat::E164);

    return $value;
  }

}

Add the process plugin to your migration yml and you're on your way!

process:
  field_phone: 
    -
      plugin: get
      source: phone
    -
      plugin: format_phone_E164
      source: phone
πŸ’¬ Support request
Status

Active

Version

2.0

Component

Documentation

Created by

πŸ‡ΊπŸ‡ΈUnited States aaronlsilber Charleston, WV

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024