You are here

public static function FieldChangeHelper::changeInstanceField in Helper 7

1 call to FieldChangeHelper::changeInstanceField()
FieldChangeHelper::mergeFields in lib/FieldChangeHelper.php

File

lib/FieldChangeHelper.php, line 289

Class

FieldChangeHelper

Code

public static function changeInstanceField(array $instance, $new_field_name) {
  $old_field = field_info_field($instance['field_name']);
  $new_field = field_info_field($new_field_name);
  if ($old_field['type'] != $new_field['type']) {
    throw new FieldException("Cannot change field instance because they are not the same field type.");
  }
  if ($old_field['storage']['type'] !== 'field_sql_storage') {
    throw new FieldException("Unable to change field type for field {$old_field['field_name']} using storage {$old_field['storage']['type']}.");
  }
  if ($new_field['storage']['type'] !== 'field_sql_storage') {
    throw new FieldException("Unable to change field type for field {$new_field['field_name']} using storage {$new_field['storage']['type']}.");
  }
  if (!field_info_instance($instance['entity_type'], $new_field_name, $instance['bundle'])) {
    $new_instance = $instance;
    $new_instance['field_name'] = $new_field_name;
    field_create_instance($new_instance);
    watchdog('helper', "Created new field instance: {$instance['entity_type']}.{$instance['bundle']}.{$new_field_name}");
  }

  // Copy data from old field tables to the new field tables.
  $old_data_table = _field_sql_storage_tablename($old_field);
  $new_data_table = _field_sql_storage_tablename($new_field);
  $query = db_select($old_data_table, 'old');
  $query
    ->fields('old');
  $query
    ->condition('entity_type', $instance['entity_type']);
  $query
    ->condition('bundle', $instance['bundle']);
  db_insert($new_data_table)
    ->from($query)
    ->execute();
  $old_revision_table = _field_sql_storage_revision_tablename($old_field);
  if (db_table_exists($old_revision_table)) {
    $new_revision_table = _field_sql_storage_revision_tablename($new_field);
    $query = db_select($old_revision_table, 'old');
    $query
      ->fields('old');
    $query
      ->condition('entity_type', $instance['entity_type']);
    $query
      ->condition('bundle', $instance['bundle']);
    db_insert($new_revision_table)
      ->from($query)
      ->execute();
  }
  FieldHelper::deleteInstance($instance);
}