Friday, March 8, 2013

How to delete a Drupal field with field_delete_instance

So here's the scenario: you've working with a bunch of other people on a Drupal site, and content types are being managed with Features.  Someone (probably you, but let's be generous and say it was someone else) has added a field to a content type that needs to be removed.  No problem!  Go into the feature, create a feature_name.install file, and add this code:

<?php

/**
 * @file
 *   Install and update scripts for the feature_name feature.
 */

/**
 * Delete my_field
 */
function feature_name_update_7001(&$sandbox) {
  // Remove the my_field field.
  field_delete_field("my_field");
  field_purge_batch(1);
}

Recreate your feature without the field you are removing, run update.php, and there you go.

"But wait!", you say. " Stop!", you say.   That wasn't the only place I was using my_field, and I want to keep it in the other content types!!  If I run that script, it will remove all instances of the field on my site! 

You are so right.  It will.  I've been bitten by that one myself....  If you want to remove only one instance of a field, you need field_delete_instance instead, and you want it in an update script so that it only fires once.

<?php

/**
 * @file
 *      Install and update scripts for the feature_name feature.
 */

/**
 * Implements hook_update_N() to remove the my_field field from *only* the feature_name ct.
 */
function feature_name_update_7001(&$sandbox) {
  // Remove my_field from *only* the specified content type.
  $instance = field_info_instance('node', 'my_field', 'content_type_name');
  field_delete_instance($instance, TRUE);
  field_purge_batch(1);
}

The field_info_instance is this:
$instance = field_info_instance('entity_type', 'field_name', 'bundle');

Helpful hint: you can find this information in the field_config_instance table of your sites database. 

And there you have it.  The field will be removed from the specified content type, left alone everywhere else, and no one has to go in and remove it in the UI.