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