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?


1 Answer 1


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.

// 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.