diff --git a/poll.install b/poll.install index 4adea1b..fcc37d2 100644 --- a/poll.install +++ b/poll.install @@ -5,6 +5,8 @@ * Install, update, and uninstall functions for the Poll module. */ +use Drupal\poll\Entity\PollChoice; + /** * Implements hook_schema(). */ @@ -65,3 +67,57 @@ function poll_schema() { return $schema; } + +/** + * Convert choices to a separate entity type. + */ +function poll_update_8001() { + // Create the entity type. + \Drupal::entityTypeManager()->clearCachedDefinitions(); + $poll_choice = \Drupal::entityTypeManager()->getDefinition('poll_choice'); + \Drupal::entityDefinitionUpdateManager()->installEntityType($poll_choice); + + // Migrate the data to the new entity type. + $result = \Drupal::database()->query('SELECT * FROM {poll__choice}'); + foreach ($result as $row) { + $choice = PollChoice::create([ + 'langcode' => $row->langcode, + 'id' => $row->choice_chid, + 'choice' => $row->choice_choice, + ]); + $choice->enforceIsNew(TRUE); + + $choice->setChoice($row->choice_choice); + $choice->save(); + } + + $target_id_schema = [ + 'description' => 'The ID of the target entity.', + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + ]; + + // Convert the choice reference table. + $schema = \Drupal::database()->schema(); + $schema->dropField('poll__choice', 'choice_choice'); + $schema->dropField('poll__choice', 'choice_vote'); + $schema->changeField('poll__choice', 'choice_chid', 'choice_target_id', $target_id_schema); + $schema->addIndex('poll__choice', 'choice_target_id', ['choice_target_id'], ['fields' => ['choice_target_id' => $target_id_schema]]); + + // Update the field storage repository. + \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions(); + $storage_definition = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('poll')['choice']; + \Drupal::service('entity.last_installed_schema.repository')->setLastInstalledFieldStorageDefinition($storage_definition); + + // Update the stored field schema. + // @todo: There has to be a better way to do this. + $field_schema = \Drupal::keyValue('entity.storage_schema.sql')->get('poll.field_schema_data.choice'); + unset($field_schema['poll__choice']['fields']['choice_chid']); + unset($field_schema['poll__choice']['fields']['choice_choice']); + unset($field_schema['poll__choice']['fields']['choice_vote']); + unset($field_schema['poll__choice']['indexes']['choice_chid']); + $field_schema['poll__choice']['fields']['choice_target_id'] = $target_id_schema; + $field_schema['poll__choice']['indexes']['choice_target_id'] = ['choice_target_id']; + \Drupal::keyValue('entity.storage_schema.sql')->set('poll.field_schema_data.choice', $field_schema); +}