You are here

function commerce_coupon_update_7002 in Commerce Coupon 7

Implements hook_update_N(). Remove coupon type id field and update coupon reference field.

File

./commerce_coupon.install, line 155
Install, update and uninstall functions for the commerce_coupon module.

Code

function commerce_coupon_update_7002(&$sandbox) {

  // Remove type_id from coupon type table and set type as primary key.
  db_drop_field('commerce_coupon_type', 'type_id');
  db_drop_unique_key('commerce_coupon_type', 'type');
  db_drop_primary_key('commerce_coupon_type');
  db_add_primary_key('commerce_coupon_type', array(
    'type',
  ));

  // Update commerce_coupon_reference not to be a text field anymore.
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'commerce_line_item')
    ->propertyCondition('type', 'commerce_coupon')
    ->execute();

  // Get all line items from the system.
  $line_items = commerce_line_item_load_multiple(array_keys($result['commerce_line_item']));

  // Store an array with the line item id and the coupon id.
  $values = array();
  foreach ($line_items as $line_item) {
    $value = array(
      'line_item_id' => $line_item->line_item_id,
      'coupon_id' => $line_item->commerce_coupon_reference[LANGUAGE_NONE][0]['value'],
    );
    $values[] = $value;
  }

  // Remove old field and force a new creation, no way to rename it.
  // see http://drupal.org/node/1201898
  field_delete_field('commerce_coupon_reference');
  commerce_coupon_line_item_configuration();

  // Finally restore the line item values.
  foreach ($values as $value) {
    $line_item = commerce_line_item_load($value['line_item_id']);
    $line_item->commerce_coupon_reference[LANGUAGE_NONE][0]['coupon_id'] = $value['coupon_id'];
    commerce_line_item_save($line_item);
  }
}