Convert a Plain Text field to a Formatted (Rich) one

Last updated on 22/11/2018

     String and text fields have different table structure (additional format column) so, to convert a "Text (plain)" to "Text (formatted)" you have to create a new field and migrate the old data in it.
Here is a snippet of how would you migrate the data from a Plain Text field(field_my_old_field) to a new Formatted Text field(field_my_new_field) by using the configuration YML files of exported fields.

     Please note that if you have a deployment workflow and you do it in HOOK_update() then, you have to ensure the Database updates are triggered before the configurations are imported.

/**
 * Implements hook_update().
 */
function HOOK_update_8001() {
 
  try {
    $config_path = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
    $source = new FileStorage($config_path);
    $entityManager = \Drupal::entityTypeManager();
 
    // Create field storage.
    $entityManager->getStorage('field_storage_config')->create($source->read('field.storage.node.field_my_new_field'))->save();
 
    // Create field instances.
    $entityManager->getStorage('field_config')->create($source->read('field.field.node.content_type_1.field_my_new_field'))->save();
    $entityManager->getStorage('field_config')->create($source->read('field.field.node.content_type_2.field_my_new_field'))->save();
  }
  catch (Exception $e) {
    // Just making sure this won't brake anything.
  }
 
  $nids = \Drupal::entityQuery('node')->condition('type', [
    'content_type_1',
    'content_type_2',
  ], 'IN')->execute();
 
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
  $cnt = 0;
 
  /** @var \Drupal\node\Entity\Node $node */
  foreach ($nodes as $node) {
    if ($node->hasField('field_my_new_field') && !$node->get('field_my_new_field')->isEmpty()) {
      continue;
    }
 
    $node->field_my_new_field->value = $node->field_my_old_field->value;
    $node->field_my_new_field->format = 'plain_text';
    $node->save();
    ++$cnt;
  }
 
  drupal_set_message($cnt . ' fields migrated.');
}