Skip to content

Instantly share code, notes, and snippets.

@jacerider
Last active May 30, 2023 11:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacerider/78b926acbb201666a0fc3a1f8102cb44 to your computer and use it in GitHub Desktop.
Save jacerider/78b926acbb201666a0fc3a1f8102cb44 to your computer and use it in GitHub Desktop.
Programmatically remove a field in Drupal 8.
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

$bundles = ['user'];

$fields['user_picture'] = [
  'entity_type' => 'user',
];

foreach ($bundles as $bundle) {
  foreach ($fields as $field_name => $config) {
    $field = FieldConfig::loadByName($config['entity_type'], $bundle, $field_name);
    if (!empty($field)) {
      $field->delete();
    }
  }
}

foreach ($fields as $field_name => $config) {
  $field_storage = FieldStorageConfig::loadByName($config['entity_type'], $field_name);
  if (!empty($field_storage)) {
    $field_storage->delete();
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment