2 * Implements hook_update_N().
4 function {{ machine_name }}_update_N(&$sandbox) {
5 // For non-batch updates, the signature can simply be:
6 // function {{ machine_name }}_update_N() {
8 // Example function body for adding a field to a database table, which does
9 // not require a batch operation:
12 'description' => "New Col",
16 $schema = Database::getConnection()->schema();
17 $schema->addField('mytable1', 'newcol', $spec);
19 // Example of what to do if there is an error during your update.
20 if ($some_error_condition_met) {
21 throw new UpdateException('Something went wrong; here is what you should do.');
24 // Example function body for a batch update. In this example, the values in
25 // a database field are updated.
26 if (!isset($sandbox['progress'])) {
27 // This must be the first run. Initialize the sandbox.
28 $sandbox['progress'] = 0;
29 $sandbox['current_pk'] = 0;
30 $sandbox['max'] = Database::getConnection()->query('SELECT COUNT(myprimarykey) FROM {mytable1}')->fetchField() - 1;
33 // Update in chunks of 20.
34 $records = Database::getConnection()->select('mytable1', 'm')
35 ->fields('m', ['myprimarykey', 'otherfield'])
36 ->condition('myprimarykey', $sandbox['current_pk'], '>')
38 ->orderBy('myprimarykey', 'ASC')
40 foreach ($records as $record) {
41 // Here, you would make an update something related to this record. In this
42 // example, some text is added to the other field.
43 Database::getConnection()->update('mytable1')
44 ->fields(['otherfield' => $record->otherfield . '-suffix'])
45 ->condition('myprimarykey', $record->myprimarykey)
48 $sandbox['progress']++;
49 $sandbox['current_pk'] = $record->myprimarykey;
52 $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
54 // To display a message to the user when the update is completed, return it.
55 // If you do not want to display a completion message, return nothing.
56 return t('All foo bars were updated with the new suffix');