Deleting Drupal Fields Programmatically

Public

Sometimes you have to delete fields programmatically. It's usefull for example when you have to change a field type (integer to float...).
source: http://data.agaric.com/deleting-drupal-fields-programmatically-so-change...

Get raw version
php
  1. /**
  2. * Implements hook_update_N().
  3. *
  4. * Based on 6.x-era code from Fox,
  5. * http://drupal.foxinbox.org/drupal/code-snippits/remove-fieldsgroup-code
  6. */
  7. function module_name_update_7001() {
  8. $fields_to_delete = array(
  9. 'field_cost',
  10. 'field_construction_budget',
  11. 'field_construction_cost',
  12. 'field_total_budget',
  13. );
  14. foreach ($fields_to_delete as $field_name) {
  15. $infos = field_info_field($field_name);
  16. if (!empty($infos)) {
  17. field_delete_field($field_name);
  18. watchdog('module_name', 'Deleted the :field_name field from all content type instances.', array(':field_name' => $field_name));
  19. }
  20. }
  21.  
  22. // The fields aren't really deleted until the purge function runs, ordinarily
  23. // during cron. Count the number of fields we need to purge, and add five in
  24. // case a few other miscellaneous fields are in there somehow.
  25. field_purge_batch(count($fields_to_delete) + 5);
  26. }