Skip to main content

Drupal 7 hook_update() snippets for features and configuration management

Published on 2016-12-08

Here some snippets that we use for things that Features module cannot do.

The Features module can install/create things for you, but it will not remove things that are not declared in Features. Note that the behavior of Drupal 8 Configuration Management is different. Drupal 8 CM *will* delete things that are not declared.

Most of those actions we perform in hook_update() and are related to 'clean-up' actions like removing a field.

<?php

/**
 * Remove field.
 *
 * Deletes a field with all it's instances.
 */
$field_list = array(
  'field_name_1',
  'field_name_2',
);
foreach ($field_list as $field) {
  field_delete_field($field);
}


/**
 * Remove field-instance.
 *
 * Delete a field-instance (and removes field_base only if there or no other
 * instances).
 */
$field_instances_list = array(
  array(
    'entity_type' => 'node',
    'field_name' => 'body',
    'bundle_name' => 'page',
  ),
);
foreach ($field_instances_list as $info) {
  if ($instance = field_info_instance($info['entity_type'], $info['field_name'], $info['bundle_name'])) {
    field_delete_instance($instance);
  }
}


/**
 * Remove Views.
 */
$views_list = array(
  'view_name_1',
  'view_name_2',
);
foreach ($views_list as $view_name) {
  if ($view = views_get_view($view_name)) {
    views_delete_view($view);
  }
}


/**
 * Remove variable.
 */
$variable_list = array(
  'variable_name_1',
  'variable_name_2',
);
foreach ($variable_list as $variable) {
  variable_del($variable);
}


/**
 * Uninstall a module.
 */
$modules = array(
  'module_1',
  'module_2',
);
foreach ($modules as $module) {
  if (module_exists($module)) {
    module_disable(array($module));
    drupal_uninstall_modules(array($module));
  }
}


/**
 * Remove Context.
 */
$context_list = array(
  'context_name_1',
  'context_name_2',
);
foreach ($context_list as $context_name) {
  if ($context = context_load('motorcycle_manuals')) {
    context_delete($context);
  }
}


/**
 * Uninstall a Language.
 */
$langcode_list = array(
  'sp',
  'fr',
);
// Will remove Spanish and French language.
module_load_include('admin.inc', 'locale');
foreach ($langcode_list as $langcode) {
  $form_state['values']['langcode'] = $langcode;
  locale_languages_delete_form_submit(array(), $form_state);
}


/**
 * Uninstall a Locale translation by Identifier.
 *
 * See database tables "locales_source" and "locales_target".
 */
$locale_translation_list = array(
  'lid_1',
  'lid_2',
);
module_load_include('admin.inc', 'locale');
foreach ($locale_translation_list as $lid) {
  $form_state['values']['lid'] = $lid;
  locale_translate_delete_form_submit(array(), $form_state);
}


/**
 * Uninstall a theme.
 */
$themes = array(
  'theme_1',
);
foreach ($themes as $theme) {
  if (drupal_theme_access($theme)) {
    theme_disable(array($theme));
  }
}