You are here

Fields: delete an instance of a field

Submitted by nicolas on Sun, 10/02/2011 - 14:27

When working on a site, there was a feature that enabled a new content type with certain fields. Apparently there was no need for a body field on the content type. I recreated the feature, but when deploying this feature, it will not remove the body field, as this could mean a loss of data.

I had to make use of hook_update to remove the field. Since it was a drupal 7 site, this means using the Field API. But in order to do this programmatically, you first need to understand the terminology.

When looking for deleting a field, you'll find some code. I was looking for "deleting a field", but this isn't really what we're trying to do.

In drupal, you can create a field, and you can use it on all content types you like. When removing the field from a content type, you are just removing an instance of the field. Removing the field, would mean: deleting the definition of the field.

To rephrase my problem: I wanted to remove the instance of a field from my content type.

Once this is clear it's only a piece of cake:

/**
* Remove the instance of the body field from my_content_type
*/
function my_feature_update_7000() {
  $instance = field_info_instance('node', 'body', 'my_content_type');
  field_delete_instance($instance);
}

 

Blog category:

Technology: