726e66daa64a5a1f4982d9a181ee8b70959c98b7
[yaffs-website] / vendor / chi-teck / drupal-code-generator / templates / d8 / hook / update_N.twig
1 /**
2  * Implements hook_update_N().
3  */
4 function {{ machine_name }}_update_N(&$sandbox) {
5   // For non-batch updates, the signature can simply be:
6   // function {{ machine_name }}_update_N() {
7
8   // Example function body for adding a field to a database table, which does
9   // not require a batch operation:
10   $spec = [
11     'type' => 'varchar',
12     'description' => "New Col",
13     'length' => 20,
14     'not null' => FALSE,
15   ];
16   $schema = Database::getConnection()->schema();
17   $schema->addField('mytable1', 'newcol', $spec);
18
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.');
22   }
23
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;
31   }
32
33   // Update in chunks of 20.
34   $records = Database::getConnection()->select('mytable1', 'm')
35     ->fields('m', ['myprimarykey', 'otherfield'])
36     ->condition('myprimarykey', $sandbox['current_pk'], '>')
37     ->range(0, 20)
38     ->orderBy('myprimarykey', 'ASC')
39     ->execute();
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)
46       ->execute();
47
48     $sandbox['progress']++;
49     $sandbox['current_pk'] = $record->myprimarykey;
50   }
51
52   $sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
53
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');
57 }