Skip to content

Instantly share code, notes, and snippets.

@teknikqa
Last active July 9, 2017 07:11
Show Gist options
  • Save teknikqa/bfbfeca6f966d21fb51bcd9175ee6619 to your computer and use it in GitHub Desktop.
Save teknikqa/bfbfeca6f966d21fb51bcd9175ee6619 to your computer and use it in GitHub Desktop.
Source: https://www.bluespark.com/blog/uninstalling-and-purging-field-modules-all-once
The job is divided in three parts: The data definition, field data purge and module list clean.
In the data definition task we provide all the required data we need to perform the task, the name of the field to delete, and given that
information, we get the field_info array and the name of the module to be uninstalled. Finally, field_delete_field() is executed.
After that the field data is purged in the batch body, and since we don't know how much data we will have to purge, we remove just 100
database rows per batch execution. After each purge we check if all the data has been removed to decide if we have to remove more data
from the database or continue to the final part.
Once all the data and metadata related to the module is removed from the database, the Drupal field types dependency is gone and we are
granted the ability to disable and uninstall our module cleanly. Finally, we can drop the empty field_deleted_data_XX and
field_deleted_revision_XX tables to keep our database clean.
Using this approach, we have two key benefits: a. we are sure that the module is disabled and our database is clean, and b. we are
confident that we can remove the module from our repository, given that in the next deploy we won't get any dependency conflict with that
module.
<?php
/**
* Removes my_field and uninstalls its module.
*/
function my_module_update_70XX(&$sandbox) {
// If this is the first pass through this update function then set some variables.
if (!isset($sandbox['total'])) {
$sandbox['field_name'] = 'my_field';
$sandbox['field'] = field_info_field($sandbox['field_name']);
$sandbox['module'] = array($sandbox['field']['module']);
field_delete_field($sandbox['field_name']);
}
field_purge_batch(100);
$sandbox['#finished'] = field_read_field($sandbox['field_name'], array('include_deleted' => 1)) ? 0 : 1;
if ($sandbox['#finished'] === 1) {
module_disable($sandbox['module']);
drupal_uninstall_modules($sandbox['module']);
db_drop_table('field_deleted_data_' . $sandbox['field']['id']);
db_drop_table('field_deleted_revision_' . $sandbox['field']['id']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment