2

I want to delete field from my Content Type using hook_update and wondering how to do it in most correct way.

I know that my field is only on 1 Content Type (page).

Here is my current solution.

function site_deployment_update_7001() {
  $fieldname = 'field_landing_page';

  if ($field = field_info_instance('node', $fieldname, 'page')) {
      field_delete_instance($field);
  }

  if ($field = field_info_field($fieldname)) {
    field_delete_field($field);
  }
}

However I'm a bit confused if I need to do field_delete_field after field_delete_instance. It's because on Drupal.org says that field_delete_instance doing field_delete_field as well (with condition: condition count($field['bundles']) == 0). I'm wondering about this condition, in what cases it is 0?

https://api.drupal.org/api/drupal/modules!field!field.crud.inc/function/field_delete_instance/7

function field_delete_instance($instance, $field_cleanup = TRUE) {
  // Mark the field instance for deletion.
  db_update('field_config_instance')->fields(array('deleted' => 1))->condition('field_name', $instance['field_name'])->condition('entity_type', $instance['entity_type'])->condition('bundle', $instance['bundle'])->execute();

  // Clear the cache.
  field_cache_clear();

  // Mark instance data for deletion.
  $field = field_info_field($instance['field_name']);
  module_invoke($field['storage']['module'], 'field_storage_delete_instance', $instance);

  // Let modules react to the deletion of the instance.
  module_invoke_all('field_delete_instance', $instance);

  // Delete the field itself if we just deleted its last instance.
  if ($field_cleanup && count($field['bundles']) == 0) {
    field_delete_field($field['field_name']);
  }
}

Please advise what are the best approach to delete field. Thanks!

3

As fields can be attachted to differents bundles

field_delete_instance deletes the field itself only when there no more bundles using it. maybe see field_info_field and this comment from field_delete_instance to clarify

So if in

 if ($field = field_info_instance('node', $fieldname, 'page')) {
   field_delete_instance($field);
 }

Applies and delete the last instance then in

  if ($field = field_info_field($fieldname)) {
    field_delete_field($field);
  }

Should be null and wont execute field_delete_field($field);

  • Thanks! I just figured out that field_delete_field does field_delete_instance first and only then delete data. – Dmytro Pastovenskyi Jan 13 '15 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.