Obviously, using the content type editor in Drupal, it’s very easy to add or remove fields visually, but this approach is not practical when working in a team with multiple environments.
It is also well known that Features is our ally in these cases in Drupal 7. The big problem is that Features works great for adding new fields, but not so much for removing fields that are no longer used. Features has no way of knowing that a field should be deleted in another environment.
Therefore, if we want to remove fields from a content type, we must do it via code using a hook_update
. The code to delete a field is very simple, something like this:
if (field_info_field('field_my_field_name')) {
field_delete_field('field_my_field_name');
}
This will do the job, but keep in mind that a field has instances, and for each content type that uses it (remember fields can be reused), there is an instance. The problem with the snippet above is that deleting the field removes it from all content types, and maybe we only want to delete it from one specific content type. If this is your case, the snippet to use is the following:
if ($instance = field_info_instance('node', 'field_my_field_name', 'node_type_name')) {
field_delete_instance($instance);
}
This will remove the field field_my_field_name from the content type node_type_name. If another content type uses the same field, it will remain available. If no other content type uses the field, it will be completely deleted.
Recommendation: Always use the second approach, as it avoids accidentally deleting a field from another content type.
More info: Drupal API - field_delete_instance