I have an Article content type for which I want to change the machine name of its fields. I created new fields with a different machine name.
How do I copy the old fields to the new fields?
You can run this, in hook_update_N():
$storage = \Drupal::entityTypeManager()->getStorage('node');
// Load all the nodes IDs for nodes that don't have the new value set.
$nids = $storage->getQuery()
// Load all nodes for which the new field has no value.
->notExists('new_field_name')
->execute();
// Loop through the nodes.
foreach ($nids as $nid) {
// Load the current node.
$node = $storage->load($nid);
// Set the new field name to the old field name and save.
$node->set('new_field_name', $node->get('old_field_name')->value)
->save();
}