You are here

function commerce_pricelist_update_8201 in Commerce Pricelist 8.2

Replace the 'customer_role' field with the 'customer_roles' field.

File

./commerce_pricelist.install, line 18
Install, update and uninstall functions for the Pricelist module.

Code

function commerce_pricelist_update_8201() {
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();

  // Create the customer_roles field.
  $storage_definition = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Customer roles'))
    ->setDescription(t('The customer roles for which the price list is valid.'))
    ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
    'type' => 'options_buttons',
  ]);
  $definition_update_manager
    ->installFieldStorageDefinition('customer_roles', 'commerce_pricelist', 'commerce_pricelist', $storage_definition);

  // Seed the new field manually, because Drupal core doesn't support
  // using setInitialValueFromField() on a multivalue field.
  $database = \Drupal::database();
  $role_ids = $database
    ->select('commerce_pricelist', 'cp')
    ->fields('cp', [
    'id',
    'type',
    'customer_role',
  ])
    ->where('cp.customer_role IS NOT NULL')
    ->execute()
    ->fetchAllAssoc('id');
  $insert_query = $database
    ->insert('commerce_pricelist__customer_roles')
    ->fields([
    'bundle',
    'deleted',
    'entity_id',
    'revision_id',
    'langcode',
    'delta',
    'customer_roles_target_id',
  ]);
  foreach ($role_ids as $id => $data) {
    $insert_query
      ->values([
      $data->type,
      0,
      $id,
      $id,
      'und',
      0,
      $data->customer_role,
    ]);
  }
  $insert_query
    ->execute();

  // Remove the customer_role field.
  $storage_definition = BaseFieldDefinition::create('entity_reference')
    ->setName('customer_role')
    ->setTargetEntityTypeId('commerce_pricelist')
    ->setLabel(t('Customer role'))
    ->setDescription(t('The customer role for which the price list is valid.'))
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
    'type' => 'options_select',
  ]);
  $definition_update_manager
    ->uninstallFieldStorageDefinition($storage_definition);
}