1

I have a content type "Article" with fields and data that was migrated from a Drupal 7 website.

  1. In the admin/structure/types/manage/article/fields I added a new text field called "Test" with default value some of some HTML added.
  2. Then, I went to manage form display and disabled that field from the form
  3. Then I went to manage display of the appropriate view mode and enabled that field.
  4. Flushed the cache

Reloading the article page doesn't display the newly added field. I believe it is because there is no value in it, but shouldn't adding a default value to the field pre-populate that field for all previous content belonging to that content type? Or am I missing something here?

3

Adding a default value doesn’t actually set any value in the field. To do that you must either edit the nodes you want the field on and click save, or write an update hook that sets the field value on all the nodes.

An update hook must be placed in a custom module’s .install file, in your case it would be something like:

function MY_MODULE_update_N() {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties('type' => 'article');
  foreach ($nodes as $node) {
    $node->set('field_name', $value);
    $node->save();
  }
}

As @4k4 mentioned if you have to update too many nodes as you have memory to, you can create batch updates using the &$sandbox, click here for more information

  • 1
    If you have more than a few nodes you might run out of memory. Then you need to update in batches via the &$sandbox parameter of the update hook, see the API docs api.drupal.org/api/drupal/… – 4k4 May 26 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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