annotate vendor/chi-teck/drupal-code-generator/templates/d7/hook/update_N.twig @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents c75dbcec494b
children
rev   line source
Chris@0 1 /**
Chris@0 2 * Implements hook_update_N().
Chris@0 3 */
Chris@0 4 function {{ machine_name }}_update_N(&$sandbox) {
Chris@0 5 // For non-multipass updates, the signature can simply be;
Chris@0 6 // function {{ machine_name }}_update_N() {
Chris@0 7
Chris@0 8 // For most updates, the following is sufficient.
Chris@0 9 db_add_field('mytable1', 'newcol', array('type' => 'int', 'not null' => TRUE, 'description' => 'My new integer column.'));
Chris@0 10
Chris@0 11 // However, for more complex operations that may take a long time,
Chris@0 12 // you may hook into Batch API as in the following example.
Chris@0 13
Chris@0 14 // Update 3 users at a time to have an exclamation point after their names.
Chris@0 15 // (They're really happy that we can do batch API in this hook!)
Chris@0 16 if (!isset($sandbox['progress'])) {
Chris@0 17 $sandbox['progress'] = 0;
Chris@0 18 $sandbox['current_uid'] = 0;
Chris@0 19 // We'll -1 to disregard the uid 0...
Chris@0 20 $sandbox['max'] = db_query('SELECT COUNT(DISTINCT uid) FROM {users}')->fetchField() - 1;
Chris@0 21 }
Chris@0 22
Chris@0 23 $users = db_select('users', 'u')
Chris@0 24 ->fields('u', array('uid', 'name'))
Chris@0 25 ->condition('uid', $sandbox['current_uid'], '>')
Chris@0 26 ->range(0, 3)
Chris@0 27 ->orderBy('uid', 'ASC')
Chris@0 28 ->execute();
Chris@0 29
Chris@0 30 foreach ($users as $user) {
Chris@0 31 $user->name .= '!';
Chris@0 32 db_update('users')
Chris@0 33 ->fields(array('name' => $user->name))
Chris@0 34 ->condition('uid', $user->uid)
Chris@0 35 ->execute();
Chris@0 36
Chris@0 37 $sandbox['progress']++;
Chris@0 38 $sandbox['current_uid'] = $user->uid;
Chris@0 39 }
Chris@0 40
Chris@0 41 $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
Chris@0 42
Chris@0 43 // To display a message to the user when the update is completed, return it.
Chris@0 44 // If you do not want to display a completion message, simply return nothing.
Chris@0 45 return t('The update did what it was supposed to do.');
Chris@0 46
Chris@0 47 // In case of an error, simply throw an exception with an error message.
Chris@0 48 throw new DrupalUpdateException('Something went wrong; here is what you should do.');
Chris@0 49 }