Drupal - How do you programmatically delete a field?

Drupal 8 is using object-oriented programming (except for some procedural bootstrapping files and the *.module and *.theme files).

When trying to access static methods of a class without a namespace, the class is expected to reside within the same namespace of the file you use the class name with.

This is not true for classes provided by Drupal core or other modules, when you use them within your own module.

So you have to properly use namespaces. When checking the API docs for example for FieldStorageConfig and scroll a little down, you will find the correct namespace of this class. The same goes for the FieldConfig class.

So you could use both classes by altering your source code to:

// Deleting field storage.
\Drupal\field\Entity\FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
\Drupal\field\Entity\FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

However, it is best-practice to not prefix the class names by their full namespace, but use use directives at the top of your source code (after a possibly existing namespace declaration, if you are within the context of an own class).

This sums up to the following correct and working example:

use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

// Deleting field storage.
FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

PS.: When learning Drupal 8, it is always a good idea to check how other modules/core are doing it. You can search the code base for the class in question or use the API reference, which has a search function, and you may find plenty useful examples.

Tags:

Entities

8