Remove Field Instance programatically during update

Public
</> CopyGet raw version
php
  1. <?php
  2.  
  3. /**
  4.  * Remove unused fields.
  5.  */
  6. function mymodule_update_N() {
  7. $fields_to_remove = array(
  8. 'contenttype_machine_name' => 'field_machine_name',
  9. );
  10. mymodule_remove_field($fields_to_remove);
  11. }
  12.  
  13. /**
  14.  * Remove field instances from content types. If field has no
  15.  * instances after remove, next cron run shall remove field for good.
  16.  *
  17.  * @param array $fields_to_remove removed fields as content type / field pair.
  18.  */
  19. function mymodule_remove_field($fields_to_remove) {
  20. foreach ($fields_to_remove as $type_name => $field_name) {
  21. $instance = field_info_instance('node', $field_name, $type_name);
  22. field_delete_instance($instance, TRUE);
  23. watchdog('MyModule', 'Removed the :field_name field from :type_name content type.', array(':field_name' => $field_name, ':type_name' => $type_name));
  24. }
  25. }