2

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();

0

Your Answer

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

Browse other questions tagged or ask your own question.