From eaf156d503a2d71f9324fe778ae7e6a6f2c9316b Mon Sep 17 00:00:00 2001 From: Eric Bremner <ebremner@uwaterloo.ca> Date: Thu, 20 Oct 2022 11:05:02 -0400 Subject: [PATCH] ISTWCMS-5880: fixing update hook for existing sites and media --- uw_cfg_common.install | 65 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/uw_cfg_common.install b/uw_cfg_common.install index 1c622d7e..fc7c4b32 100644 --- a/uw_cfg_common.install +++ b/uw_cfg_common.install @@ -465,6 +465,46 @@ function uw_cfg_common_update_9105(&$sandbox) { */ function uw_cfg_common_update_9106(&$sandbox) { + // The database service. + $database = \Drupal::database(); + + // The tables to be used for fields to get and remove. + $tables = [ + 'node__field_uw_type_of_media', + 'node_revision__field_uw_type_of_media', + 'node__field_uw_hero_image', + 'node_revision__field_uw_hero_image', + ]; + + // Step through each of the tables and get the data, + // then truncate them. We need to truncate the table + // so that we are able to modify the fields, if there + // is data in these tables, Drupal throws an error about + // data already existing in the fields. We will insert + // the data back into the tables after everything is + // completed. + foreach ($tables as $table) { + + // Get the rows in the table. + $values = $database->select($table, 'n') + ->fields('n') + ->execute() + ->fetchAll(); + + // Step through each of the rows and add to variable. + foreach ($values as $value) { + + // Add to the variable and cast to an array so that + // we are not using an object, just makes it easier + // to work with when inserting these rows back + // into the database. + $node_data[$table][] = (array)$value; + } + + // Truncate the table. + $database->truncate($table)->execute(); + } + // The content types that are not getting any changes. $cts_not_to_install = [ 'uw_ct_sidebar', @@ -630,4 +670,29 @@ function uw_cfg_common_update_9106(&$sandbox) { $node->save(); } } + + // Step through all the tables and insert back into + // the database. + foreach ($node_data as $table => $data) { + + // Get all the rows from the table. + foreach ($data as $field_data) { + + // Reset the fields array, so we are working with + // a blank array to insert. + $fields = []; + + // Step through all the entries in the row and add + // to the fields array, this makes it much easier to + // do one insert command. + foreach ($field_data as $key => $value) { + $fields[$key] = $value; + } + + // Insert the row into the database. + $result = $database->insert($table) + ->fields($fields) + ->execute(); + } + } } -- GitLab