Skip to content

Latest commit

 

History

History
63 lines (47 loc) · 2.65 KB

4.4-essential-apis-update.md

File metadata and controls

63 lines (47 loc) · 2.65 KB

Update API

From Introduction to update API for Drupal 8:

You need to provide code that performs an update to stored data whenever your module makes a change to its data model. A data model change is any change that makes stored data on an existing site incompatible with that site's updated codebase.

Examples of data model changes may include:

  • Changes to content entities and fields
  • Changes to configuration
  • Changes to schema

hook_update_N()

All data model changes should go into a hook_update_N() function.

For example, assume you have a module called mymodule. In your mymodule.install file you would add this code:

/**
 * Briefly explain what your update does here.
 */
function mymodule_update_8001(&$sandbox) {
  // Your update code here.
}

The value of N should get set based on this criteria from Introduction to update API for Drupal 8:

  • 1 digit for Drupal core compatibility (8)
  • 1 digit for your module's major release version. For instance, if you're developing for Drupal Core and its version 8.0.x, use 0, and if its version 8.1.x, use 1, etc. If you're in a contrib or custom module, and its version 8.x-1.x, use 1, etc.
  • 2 digits for sequential counting, starting with 01. (Note: starting at 01 is required. Starting at 00 can cause system schema corruption.)

hook_post_update_NAME()

If you need to update data that doesn't affect the existing data model (for example, unpublishing a bunch of published nodes that match certain criteria), you should use hook_post_update_NAME() functions be placed in module_name.post_update.php.

The value of NAME is just an arbitrary machine name (preferably related to whatever the task is attempting to accomplish).

Just like hook_update_N() functions, Drupal ensures these functions are only ever executed once.

Here's an example from the user module:

use Drupal\user\Entity\Role;

/**
 * Enforce order of role permissions.
 */
function user_post_update_enforce_order_of_permissions() {
  $entity_save = function (Role $role) {
    $permissions = $role->getPermissions();
    sort($permissions);
    if ($permissions !== $role->getPermissions()) {
      $role->save();
    }
  };
  array_map($entity_save, Role::loadMultiple());
}

Additional Resources