Score:2

How can I capture a field’s configs and storage so I can delete it and then re-create it?

pl flag

I’m trying to implement this in a hook_update_N() but I’m not sure it’s proper (see excerpt below). Note I’m changing max_length in the process.

What I'm trying to do: update my_custom_entity.field_my_custom_field which has saved data into it. So I need to:

  1. Store that data
  2. Store the field configs - if that’s possible?
  3. Store the field storage - if that’s possible?
  4. Delete the field
  5. Create the field again using stored configs and storage
  6. Restore the saved data
  // Capture the existing field configs.
  $field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
  $new_field = $field->toArray();
  $new_field['field_type'] = 'string';
  $new_field['settings'] = [];

  // Capture the existing field storage.
  $new_field_storage = $field_storage->toArray();
  $new_field_storage['type'] = 'string';
  $new_field_storage['settings'] = [
    'max_length' => $field_length,
    'is_ascii' => FALSE,
    'case_sensitive' => FALSE,
  ];

  // Delete existing field + field storage and purge data.
  $field_storage->delete();
  field_purge_batch(150);

  // Create new field using captured configs/settings.
  $new_field_storage = FieldStorageConfig::create($new_field_storage);
  $new_field_storage->save();

  $new_field = FieldConfig::create($new_field);
  $new_field->save();
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.